【问题标题】:How to conveniently specify columns of matrices in a list?如何方便地指定列表中的矩阵列?
【发布时间】:2018-02-07 17:34:26
【问题描述】:

在计算列表ls1 的矩阵列均值时,有没有办法定义整列(例如第 2 列)而不是单元格?直觉上我尝试了sapply(ls1, "[", [, 2])sapply(ls1, "[", "[", 2)sapply(ls1, c("[", "["), 2)之类的东西,但它不起作用。

ls1 <- list(matrix(seq(1,16), ncol = 4),
            matrix(seq(17,32), ncol = 4),
            matrix(seq(33,48), ncol = 4))

colMeans(sapply(ls1, "[", 5:8))
# [1]  6.5 22.5 38.5

【问题讨论】:

    标签: r list matrix


    【解决方案1】:

    我们可以使用lapply 而不是sapply 来获取它,因为参数略有不同,即lapply 中的参数很少,以确保可以按参数顺序进行索引

    colMeans(do.call(cbind, lapply(ls1, "[", ,2)))
    

    如有疑问,匿名函数可能会有所帮助

    colMeans(sapply(ls1, function(x) x[,2]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 2014-02-08
      • 1970-01-01
      • 2019-02-10
      • 2017-05-10
      • 2012-05-03
      • 1970-01-01
      相关资源
      最近更新 更多