【问题标题】:How can I select specific columns when computing average colMeans in a list of matrices?在计算矩阵列表中的平均 colMeans 时如何选择特定列?
【发布时间】:2017-10-06 09:22:58
【问题描述】:

我有一个列表lst.mx,其中包含类似的矩阵。

lst.mx <- lapply(1:10, function(X, r = 20) {
  d = matrix(NA, nrow = r, ncol = 4, dimnames = list(NULL, c("fee", "fi", "fo", "fum")))
  d[, 1] = rbinom(r, 1, .375)
  d[, 2] = .42 * rnorm(r, 0, 6)
  d[, 3] = rbinom(r, 11, c(1:11)/11)
  d[, 4] = rbinom(r, 1, .3)
  d
})

当我想要一个矩阵中特定列的平均值时,我使用 e。 G。 colMeans(lst.mx[[1]][, 2:3])

现在因为round(rowMeans(sapply(lst.mx[, 2:3], colMeans)), 3) 抛出一个Error in lst.mx[, 2:3] : incorrect number of dimensions 并且奇怪的是dim(lst.mx)NULL -

如何选择sapply() 中的特定列来计算它们在整个列表中的平均平均值?

注意:round(rowMeans(sapply(lst.mx, colMeans)), 3) 工作正常。

编辑: 好的@akruns 解决方案我用rowMeans(sapply(lst.mx, function(x) colMeans(x[, 2:3]))) 完成了它

忘了说,我现在想以特定列为条件。我用sapply(lst.mx, function(x) colMeans(x[, 2:3][x[, 1] == 0])) 直观地尝试了它,这又给了这个人:Error in colMeans(x[, 2:3][x[, 1] == 0]) : 'x' must be an array of at least two dimensions

其实我想要这个(可能有一个我不知道的包?):

# average colMeans of list conditioned on column one
# fee          fi          fo 
#   0  ?.????????  ?.????????   
#   1  ?.????????  ?.????????

【问题讨论】:

  • 使用匿名电话lapply(lst.mx, function(x) colMeans(x[,2:3]))
  • rowMeans(sapply(lst.mx, function(x) colMeans(x[, 2:3]))) - 谢谢!
  • 好的,如何正确设置sapply(lst.mx, function(x) colMeans(x[, 2:3][x[, 1] == 0]))? (仅表示第一列 = 0 的值)

标签: r list matrix sapply


【解决方案1】:

您只是指定了错误的子集。 试试这个:

lapply(lst.mx, function(x) colMeans(x[x[,1] == 0,][,2:3]))

注意:首先我用行 == 0 对列 == 1 进行子集化,然后提取第 2 列和第 3 列,最后应用 colMeans。

【讨论】:

    猜你喜欢
    • 2013-01-04
    • 2021-03-16
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    • 2014-03-15
    • 2017-08-21
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多