如何使用分组数据生成滚动平均值.这是数据
set.seed(31)
dd<-matrix(sample(seq(1:20),30,replace=TRUE),ncol=3)
Run Code Online (Sandbox Code Playgroud)
添加组标识符,并按组标识符排序
du<-sample(seq(1:4),10,replace=TRUE)
d<-cbind(du,dd)
d<-d[order(d[,1]),]
Run Code Online (Sandbox Code Playgroud)
这给出了滚动平均值但忽略了组bounderis
d_roll_mean <- apply(d[,2:4], 2,
function(x) {
rollapply(zoo(x), 3, mean, partial=TRUE, align='right')
}
)
Run Code Online (Sandbox Code Playgroud)
这给出了下面的结果
# cbind(d,d_roll_mean)
# [1,] 1 3 3 12 3.000000 3.000000 12.000000
# [2,] 2 10 13 8 6.500000 8.000000 10.000000
# [3,] 2 17 2 17 10.000000 6.000000 12.333333
# [4,] 3 14 6 3 13.666667 7.000000 9.333333
# [5,] 3 6 20 1 12.333333 9.333333 7.000000
# [6,] 3 1 16 19 7.000000 14.000000 7.666667
# [7,] …Run Code Online (Sandbox Code Playgroud)