-1

我是 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 多个表,我可以使用它

4

1 回答 1

2

A loop over the individual elements of the list is conveniently performed using lapply(). You could try this:

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

data:

u <- c(1,2,3)
set.seed(123)
x <- lapply(u, replicate, rbinom(10,1,.5))
于 2016-07-18T15:13:58.633 回答