【发布时间】: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 的值)