【问题标题】:How to average the same cells over many lists of matrices in R [duplicate]如何在R中的许多矩阵列表上平均相同的单元格[重复]
【发布时间】:2020-10-07 20:10:06
【问题描述】:

我想对多个矩阵列表中的相同单元格进行平均,结果是一个具有平均单元格的矩阵。例如

x <- list()
x[[1]] <- data.frame(matrix(sample(1:7,16, replace = T),4,4))
x[[2]] <- data.frame(matrix(sample(1:7,16, replace = T),4,4))

> x[[2]]
  X1 X2 X3 X4
1  3  5  2  6
2  4  2  5  1
3  7  7  3  3
4  7  4  7  1
> x[[1]]
  X1 X2 X3 X4
1  6  5  2  7
2  7  2  7  7
3  3  5  7  1
4  5  4  1  7

我想要一个 4x4 矩阵,其中每个条目是两个列表中相同条目的平均值。

谢谢

【问题讨论】:

    标签: r list matrix average


    【解决方案1】:

    如果您想要矩阵类对象而不是 data.frame,请在输出中使用 as.matrix

    Reduce('+', x)/length(x)
    

    【讨论】:

      【解决方案2】:

      如果我们转换为array,则applymean 也有一个选项。 mean 可以用na.rm = TRUE 处理NA 元素

      apply(array(unlist(x), c(dim(x[[1]]), length(x))), 1:2, mean, na.rm = TRUE)
      #     [,1] [,2] [,3] [,4]
      #[1,]  3.0  3.5  2.5  1.5
      #[2,]  3.5  5.0  5.0  3.5
      #[3,]  3.5  4.5  5.5  6.5
      #[4,]  4.0  4.0  3.5  4.5
      

      或使用rowMeans

      t(apply(array(unlist(x), c(dim(x[[1]]), length(x))), 1, rowMeans, na.rm = TRUE))
      #    [,1] [,2] [,3] [,4]
      #[1,]  3.0  3.5  2.5  1.5
      #[2,]  3.5  5.0  5.0  3.5
      #[3,]  3.5  4.5  5.5  6.5
      #[4,]  4.0  4.0  3.5  4.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-27
        • 2015-12-03
        • 1970-01-01
        • 2018-12-06
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多