在矩阵上使用带有均值函数的mapply [英] Using mapply with mean function on a matrix
问题描述
我希望计算矩阵每一列(或行)中相邻值的平均值(例如[1,1]和[2,1],[2,1]和[3,1]的平均值, [3,1]和[4,1]),并将其应用于所有列.
I wish to calculate the mean of adjacent values in each column (or row) of a matrix (e.g. mean of [1,1] and [2,1], [2,1] and [3,1], [3,1] and [4,1]) and to apply this across all columns.
我尝试使用mapply函数(避免使用for循环),计算每列中前两个值的平均值,并计划将其逐行应用于整个矩阵.但是,如果我尝试对值求和而不是对均值函数求和,那么mapply似乎有效.
I have tried to use the mapply function (to avoid using a for loop), to calculate the mean of the first 2 values in each column, and plan to apply this to the whole matrix row-by-row. However mapply which seems to work if I try to sum the values but not for the mean function.
请参见下面的示例:
x <- matrix(c(NA,rnorm(28),NA), nrow=6, ncol=5)
print(x)
[,1] [,2] [,3] [,4] [,5]
[1,] NA -0.6557176 1.7741320 0.3667700 -0.5548408
[2,] 0.14001643 0.2521062 -0.1295084 -0.4272368 0.7598425
[3,] 0.32123196 0.5736409 0.8618268 2.1535191 0.4686728
[4,] 0.06573949 -1.2101965 -0.4308219 -0.2624877 -0.3751350
[5,] -0.66247996 1.2743463 1.6044236 1.2004990 -0.3283678
[6,] 1.05005260 1.2264607 3.2347421 -0.8113528 NA
mapply(sum, x[1,], x[2,])
[1] NA -0.40361136 1.64462358 -0.06046682 0.20500169
# gives the sum of the input of rows 1 and 2 for each column, as expected
mapply(mean, x[1,], x[2,])
[1] NA -0.6557176 1.7741320 0.3667700 -0.5548408
# gives the actual values across row 1
使用均值函数时,输出似乎是第一行的值.我怀疑问题出在索引正确的输入值上.
When using the mean function, the output appears to be the values of the first row. I suspect the problem is in indexing the correct input values.
推荐答案
您可以使用:
library(zoo)
apply(x, 2, function(x) rollapply(x, 2, mean))
这篇关于在矩阵上使用带有均值函数的mapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!