在计算矩阵列表中的平均 colMeans 时,如何 select 特定列?
How can I select specific columns when computing average colMeans in a list of matrices?
我有一个包含相似矩阵的列表 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
–
如何 select 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[x[,1] == 0,][,2:3]))
注意:首先我将列 == 1 与行 == 0 进行子集化,然后提取第 2 列和第 3 列,最后应用 colMeans。
我有一个包含相似矩阵的列表 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
–
如何 select 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[x[,1] == 0,][,2:3]))
注意:首先我将列 == 1 与行 == 0 进行子集化,然后提取第 2 列和第 3 列,最后应用 colMeans。