r - 每组 7 天移动平均线 - R

标签 r ggplot2 moving-average

我有多个分类值的每日数据,存储为数据框:

YYYYMM    Date         ID    Count
201401    01/01/2014   A     151
201401    01/01/2014   B     68
201401    01/01/2014   C     487
201401    02/01/2014   A     198
201401    02/01/2014   B     97
201401    02/01/2014   C     403

我正在尝试使用 ggplot 绘制针对实际值的移动平均值。

我想要做的是在我的数据框中创建一个第 5 列,其中包含平均值。

我已经尝试过这个解决方案(在这里找到:Constructing moving average over a categorical variable in R)
df$Mean<-0
library(plyr)
library(zoo)
ddply(
      df, "ID",
       transform,
        df$Mean<-rollmean(Count, 7, na.pad=TRUE)
     )

它可以工作,但它计算我数据框中每一列的平均值,并在现有数据框中创建另一个数据框,所以我最终得到如下结果:
YYYYMM  Date        ID  Count  Mean.YYYYMM  Mean.Date   Mean.ID  Mean.Count
201401  01/01/2014  A   151    201401       01/01/2014  B        58.90
201401  01/01/2014  B   68     201401       01/01/2014  B        62.05
201401  01/01/2014  C   487    201401       01/01/2014  B        61.84
201401  02/01/2014  A   198    201401       01/01/2014  B        58.02
201401  02/01/2014  B   97     201401       01/01/2014  B        57.65
201401  02/01/2014  C   403    201401       01/01/2014  B        59.65

当我尝试绘制此图时
for (var in unique(df$ID))
{
ggplot(df[df$ID==var,], aes(x=Date)) +
        geom_line(aes(y=Count),color="blue") +
        geom_line(aes(y=Mean$Count),color="grey",linetype="dashed") +
        facet_wrap(~ID) +
        theme_bw()
}

我收到一条错误消息。我想知道我在这里错过了什么,或者是否有另一种方法可以解决这个问题?

最佳答案

您没有提供足够的数据来在组内创建每周滚动平均值,但原则上它可以这样工作:

library(tidyverse)
library(zoo)

my_data <- my_data %>% 
  group_by(ID) %>% 
  mutate(roll_mean = rollmean(Count, 2, na.pad = T))

使用 dplyrgroup_by您的 ID 变量,然后创建一个具有滚动平均值的新列。然后您可以使用标准 ggplot2 绘制此图-句法:

ggplot(my_data, aes(Date, Count, group = 1)) +
  geom_line(colour = "blue") +
  geom_point(colour = "blue") +
  geom_point(aes(y = roll_mean), colour = "red") +
  facet_wrap(~ID)
#> Warning: Removed 3 rows containing missing values (geom_point).



数据

zzz <- "YYYYMM    Date         ID    Count
201401    01/01/2014   A     151
201401    01/01/2014   B     68
201401    01/01/2014   C     487
201401    02/01/2014   A     198
201401    02/01/2014   B     97
201401    02/01/2014   C     403"

my_data <- read_table(zzz)

关于r - 每组 7 天移动平均线 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204262/

相关文章:

r - 提取因子水平时的意外行为

r - (R) IF 语句 : stop & warn if FALSE else continue

r - 使用 ggplot 为世界地图中的特定国家添加颜色

r - 使用ggplot2创建一个facet_wrap图,每个图中都有不同的注释

TensorFlow 指数移动平均线

r - 在Linux上安装R : configure: WARNING: you cannot build PDF versions of the R manuals

r - ggplot : How to add a certain percentage to the top of the pillars of a histogram

r - 在 ggplot/Plotly 中设置图例的 alpha

r - 不规则时间序列上的条件滚动平均值(移动平均值)

algorithm - 使用简单移动平均线避免可能的精度损失