使simplify2array生成一个数字矩阵

时间:2016-07-19 13:27:28

标签: r list matrix

我想使用listmatrix中使用simplify2array中的元素并计算rowMeans。问题是,simplify2array生成matrix,其元素属于list类,而不是numeric

bar <- list(list(11, 21, 31), list(12, 22, 32))

bar_new <- simplify2array(bar)
#gives[,1] [,2]
#[1,] 11   12  
#[2,] 21   22  
#[3,] 31   32 
rowMeans(bar_new) 
#gives Error: 'x' must be numeric
# does not work as all elements in foo are lists - see class(bar_new[1, 1])

当然,解决方法是rowMeans(matrix(as.numeric(bar_new), ncol = ncol(bar_new)))。但我想保持简短。所以问题是:如何让simplify2array生成一个&#34;数字&#34; -matrix?

为完整起见,预期输出为:

foo <- matrix(c(11, 12, 21, 22, 31, 32), byrow = TRUE, nrow = 3)

#gives [,1] [,2]
#[1,]    11   12
#[2,]    21   22
#[3,]    31   32

rowMeans(foo) 
#gives 11.5 21.5 31.5
# works as all elements in foo are numeric - see class(foo[1, 1])

4 个答案:

答案 0 :(得分:2)

另一种方式:

mode(bar_new) <- "numeric"
rowMeans(bar_new)
# [1] 11.5 21.5 31.5

答案 1 :(得分:1)

似乎simplify2array不适用于嵌套列表。

以下是使用simplify2array的两种(有点愚蠢的)解决方案:

cbind(simplify2array(bar[[1]]), simplify2array(bar[[2]]))
     [,1] [,2]
[1,]   11   12
[2,]   21   22
[3,]   31   32

matrix(simplify2array(unlist(bar, recursive=F)), 3)
     [,1] [,2]
[1,]   11   12
[2,]   21   22
[3,]   31   32

当然,如果您知道每个列表项中向量的长度相等,则可以使用unlistmatrix,概括@ akrun解决方案的一部分:

matrix(unlist(bar), ncol=length(bar))

与以前的方法相比,阅读起来要清晰得多,并且与列表一起增长。

答案 2 :(得分:1)

这是一种方法:

simplify2array(Map(unlist, bar))
#      [,1] [,2]
# [1,]   11   12
# [2,]   21   22
# [3,]   31   32

str(simplify2array(Map(unlist, bar)))
# num [1:3, 1:2] 11 21 31 12 22 32

rowMeans(simplify2array(Map(unlist, bar)))
# [1] 11.5 21.5 31.5

答案 3 :(得分:1)

我们可以在没有simplify2array

的情况下执行此操作
rowMeans(matrix(unlist(bar), ncol=2))
#[1] 11.5 21.5 31.5