从 R 列表中的多个矩阵访问相同的矩阵位置?

Accessing same matrix position from multiple matrices in a list in R?

我有一个任意长度的列表,所有条目都是任意长度和宽度但彼此大小相同的矩阵。我想计算列表中每个矩阵中相同位置的值的均值、中值和众数。我可以用 for 循环来做到这一点,但是有 simpler/vectorized 方法吗?

我试过了:

for (x in 1:X){
   for (y in 1:Y){
      My_List[[B+1]][y,x] <- mean(My_List[[1:B]][y,x])
      My_List[[B+2]][y,x] <- median(My_List[[1:B]][y,x])
      My_List[[B+3]][y,x] <- mode(My_List[[1:B]][y,x])
   }
}

其中列表的长度为 B+3,矩阵的宽度均为 X,长度为 Y,但我遇到了与尝试跨列表条目访问相关的错误。我考虑过 lapply(),但我不知道如何将 sunsetting 操作变成 apply() 系列的 FUN。我可以用一个可恶的 for 循环嵌套来做到这一点,但必须有更好的方法,尤其是在 R 中。

编辑:可重现示例和预期输出:

第 1 步:生成 My_List:

Matrix_A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2)
Matrix_B <- matrix(c(2, 1, 3, 3, 6, 5), nrow = 2)
Matrix_C <- matrix(c(1, 1, 3, 3, 5, 5), nrow = 2)

# X = 3, Y = 2

B = 3

My_List <- vector(mode = "list", length = B + 3)

My_List[[1]] <- Matrix_A
My_List[[2]] <- Matrix_B
My_List[[3]] <- Matrix_C

My_List

第一步输出,注意NULL占位符空格:

[[1]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

[[2]]
     [,1] [,2] [,3]
[1,]    2    3    6
[2,]    1    3    5

[[3]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    1    3    5

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

使用与上面相同的代码块,我希望看到 My_List[[4]][1,1] 是 My_List[[1]][1,1 的平均值]、My_List[[2]][1,1] 和 My_List[[3]][1,1],因此 1 + 2 + 1 / 3 = 1.333,依此类推y 和 x 的每个组合。列表的索引 4 表示均值,5 表示中位数,6 表示众数。

我希望最终输出为:

[[1]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

[[2]]
     [,1] [,2] [,3]
[1,]    2    3    6
[2,]    1    3    5

[[3]]
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    1    3    5

[[4]] # Mean
     [,1]     [,2]     [,3]
[1,]    1.333    3.000    5.333
[2,]    1.333    3.333    5.333

[[5]] # Median
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    1    3    5

[[6]] # Mode
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    1    3    5

您可以将矩阵列表转换为 3 维数组:

i <- 2
j <- 3

n <- 4

# create list of n i*j matrices
l <- replicate(n, list(matrix(sample(10,i*j),i,j)))

# list to 3D array
arr.3d <- array(unlist(l), c(i, j, n))

apply(arr.3d, 1:2, mean)
     [,1] [,2] [,3]
[1,] 6.50 5.00 3.50
[2,] 5.25 4.25 6.75

apply(arr.3d, 1:2,median)
     [,1] [,2] [,3]
[1,]    6    5  1.5
[2,]    5    4  6.0

对于mode

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

apply(arr.3d,1:2,Mode)