首页 > 解决方案 > R - 按日期绘制列中参数的移动平均值

问题描述

假设您有一个表,其中 Result 可以在同一天取值 {a,b,c}。如何绘制 a、b 和 c 频率随时间变化的移动平均值?

例子:

Date         Result
2018-11-23   a
2018-11-23   a
2018-11-23   b
2018-11-24   c
2018-11-24   b
2018-11-25   c
2018-11-25   c
2018-11-25   b
2018-11-26   c
2018-11-26   b
2018-11-26   a
...

标签: rplotmoving-average

解决方案


我不确定你到底想要达到什么目的。但是以下内容为您提供了每个日期每个字母的计数。

library(dplyr)
library(tidyr)
library(ggplot2)

x <- structure(list(date = structure(c(17858, 17858, 17858, 17859, 
                                  17859, 17860, 17860, 17860, 17861, 17861, 17861), class = "Date"), 
               letter = c("a", "a", "b", "c", "b", "c", "c", "b", "c", "b", 
                          "a")), class = "data.frame", row.names = c(NA, -11L))

agg_x <- x %>% 
  group_by(date, letter) %>%
  summarize(count = n()) %>%
  ungroup() 

agg_x %>%
  spread(letter, count)
#> # A tibble: 4 x 4
#>   date           a     b     c
#>   <date>     <int> <int> <int>
#> 1 2018-11-23     2     1    NA
#> 2 2018-11-24    NA     1     1
#> 3 2018-11-25    NA     1     2
#> 4 2018-11-26     1     1     1

ggplot(data = agg_x, aes(x = date, y = count, color = letter)) +
  geom_point() +
  geom_line()

reprex 包创建于 2021-05-16 (v2.0.0 )


推荐阅读