【问题标题】:Taking a moving average in a nested data frame在嵌套数据框中取移动平均值
【发布时间】:2026-01-15 21:45:01
【问题描述】:
set.seed(123)
df <- data.frame(
region = rep(1:3, each = 45),
term  = rep(rep(c("a", "b", "c"), 15), 3), 
period = rep(rep(1:15, each = 3), 3),
X = rnorm(nrow(df)) 
)

我有一个嵌套数据框,其中我有 3 个变量的度量(“a”、“b”和“c”term 列,在X 列中给出了相应的度量),记录在15 个时间段和 3 个区域。我想创建一个新列X_moving_av,它分别是该区域内前 3 个时期的“a”、“b”和“c”的平均值。因此,例如,取区域 1,术语“b”,在周期 10 中。在新列 X_moving_av 中,我希望出现以下数字:

with(df, ave(X[region==1 & term=="b" & period==10], X[region==1 & term=="b" & period==9], X[region==1 & term=="b" & period==8]))

那么下面的单元格将是:

with(df, ave(X[region==1 & term=="c" & period==10], X[region==1 & term=="c" & period==9], X[region==1 & term=="c" & period==8]))

...等整个df,(不包括前2个时期,我没有3个时期的措施)。

迭代这个的最好方法是什么?我实际上在term 列中记录了很多变量(即不仅仅是“a”、“b”和“c”),还有数百个区域和周期,所以我需要尽可能通用的东西。

【问题讨论】:

    标签: r time-series apply purrr moving-average


    【解决方案1】:

    这是一个时间序列案例吗?

    如果是的话

    https://github.com/tidyverts/tsibble

    set.seed(123)
    df <- data.frame(
        region = rep(1:3, each = 45, length.out = 135),
        term  =  rep(c("a", "b", "c"), each = 3, lenght.out = 135), 
        period = rep(1:15, each = 3 , lenght.out = 135),
        x =    rnorm(135)
    )
    
    library(tsibble)
    
    Your_Answer <- df %>% 
      group_by(region,term,period) %>% 
      mutate(X_MA = slide_dbl(x, ~ mean(., na.rm = TRUE), .size = 3))
    

    【讨论】:

    • 这肯定看起来是正确的,但这不是数据集的样子。我有 3 个区域和 15 个时期,然后对于每个时期,我有三个要测量的变量。我只是想要该区域内每个变量在前 3 个时期内的平均值(即当前时期和前两个时期的平均值)。
    【解决方案2】:
    df <- data.frame(
      region = rep(1:3, each = 45),
      term  = rep(rep(c("a", "b", "c"), 15), 3), 
      period = rep(rep(1:15, each = 3), 3),
      X = rnorm(nrow(df)) 
    )
    
    Your_Answer <- df %>% 
      group_by(region,term) %>% 
      mutate(X_MA = slide_dbl(X, ~ mean(., na.rm = TRUE), .size = 3))
    

    【讨论】: