lapply 创建的矩阵中的行求和

Summing Rows in Matrices created by lapply

我是 R 的新手,我正在尝试找出如何对以下输出中的行求和。

u <- c(1,2,3)
x <- lapply(u, replicate, rbinom(10,1,.5))

当我这样做时,x 等于

[[1]]
      [,1]
 [1,]    0
 [2,]    0
 [3,]    1
 [4,]    1
 [5,]    0
 [6,]    1
 [7,]    1
 [8,]    1
 [9,]    1
[10,]    0

[[2]]
      [,1] [,2]
 [1,]    0    1
 [2,]    0    1
 [3,]    1    0
 [4,]    1    1
 [5,]    1    1
 [6,]    1    1
 [7,]    1    1
 [8,]    1    0
 [9,]    1    0
[10,]    0    0

[[3]]
      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    1    1    1
 [3,]    1    0    1
 [4,]    1    0    1
 [5,]    0    0    1
 [6,]    0    0    1
 [7,]    0    1    0
 [8,]    1    1    1
 [9,]    0    1    1
[10,]    0    1    1

当我使用编码时

rowSums(x)

rowSums(x[2])

我收到这个错误

Error in rowSums(x) : 'x' must be an array of at least two dimensions

如何对行求和?另外,有没有办法分解表格,以便我可以进行单独分析。最好是一种非手动方式,这样如果我有 100 多个表就可以使用它

使用lapply() 可以方便地对列表的各个元素执行循环。你可以试试这个:

lapply(x, rowSums)
#[[1]]
# [1] 0 1 0 1 1 0 1 1 1 0
#
#[[2]]
# [1] 2 1 2 2 1 2 1 1 0 1
# 
#[[3]]
# [1] 1 1 2 1 1 0 1 1 1 1

数据:

u <- c(1,2,3)
set.seed(123)
x <- lapply(u, replicate, rbinom(10,1,.5))