计算矩阵中的滚动平均值

Calculate rolling average in matrix

我想计算滚动平均值。具体来说,我想用前 3 列的滚动平均值填充 Mat1 第 5 列和第 6 列的 每一行 。对于第 5 列,这意味着 2、3、4 的平均值,对于第 6 列,这意味着第 3、4、5 列的平均值。我只想在计算平均值的列中没有 NA 时计算平均值。

mat1 <- data.frame(matrix(nrow =6, ncol =6))
mat1[1:4,1:4] = rnorm(16,0,1)
mat1[5:6,1:3] = rnorm(6,0,1)
mat1 

        X1          X2          X3         X4 X5 X6
1  0.40023542  2.05111693 0.695422777  0.9938004 NA NA
2  0.22673283 -0.86433614 0.002620227  0.8464388 NA NA
3  0.88522293 -0.72385091 0.751663489  1.3240476 NA NA
4  0.65373734  1.68385938 0.759718967 -0.4577604 NA NA
5 -0.09442161  0.72186678 0.180312264         NA NA NA
6  0.39930843  0.04311092 2.141065229         NA NA NA

条目 1,5 = mean(2.051,0.69,0.99) 和条目 1,6 = mean(0.69, 0.99, mean(2.051,0.69,0.99))。

我们可以使用for循环来计算最后三列的滚动平均值

cols <- 5:6
for(i in cols) {
   mat1[i] <- rowMeans(mat1[(i-3):(i-1)])
}

mat1
#           X1          X2          X3         X4           X5        X6
#1  0.40023542  2.05111693 0.695422777  0.9938004  1.246780036 0.9786677
#2  0.22673283 -0.86433614 0.002620227  0.8464388 -0.005092371 0.2813222
#3  0.88522293 -0.72385091 0.751663489  1.3240476  0.450620060 0.8421104
#4  0.65373734  1.68385938 0.759718967 -0.4577604  0.661939316 0.3212993
#5 -0.09442161  0.72186678 0.180312264         NA           NA        NA
#6  0.39930843  0.04311092 2.141065229         NA           NA        NA

这个 returns NA 如果任何 NA 值出现在评论中提到的计算中。如果我们需要忽略 NA 值,我们可以在 rowMeans.

中设置 na.rm = TRUE

数据

mat1 <- structure(list(X1 = c(0.40023542, 0.22673283, 0.88522293, 0.65373734, 
-0.09442161, 0.39930843), X2 = c(2.05111693, -0.86433614, -0.72385091, 
 1.68385938, 0.72186678, 0.04311092), X3 = c(0.695422777, 0.002620227, 
0.751663489, 0.759718967, 0.180312264, 2.141065229), X4 = c(0.9938004, 
0.8464388, 1.3240476, -0.4577604, NA, NA), X5 = c(NA, NA, NA, 
NA, NA, NA), X6 = c(NA, NA, NA, NA, NA, NA)), class = "data.frame", 
row.names = c("1", "2", "3", "4", "5", "6"))