R:递归索引在级别 2 失败



我创建了一个矩阵列表,我希望能够对它们应用操作,我想做的一件事是使用 cbin 和 rbind 等运算符将它们组合在一起,一种方法是另一种方式,但我只想将矩阵保存在列表中并应用操作而不编写每个人。

'Combinedmatrix<-cbind(elementlist[[1]],...,elementlist[[n]])'

有没有办法做同样的事情而不是写列表的每个元素?我试了下一个

'(i in 1:length(list)){combinedmatrix<-cbind(list[[i]])}'

在这种情况下,它只接受最后一个元素,不做更多的事情,我尝试的另一种方法是:

'i<-1:length(list)'
'combinedmatrix<-cbind(list[[i]])}'

在这种情况下出现

'Error in list[[i]] : recursive indexing failed at level 2'
您可以使用

purrr包中的reduce()。假设矩阵列表mlist

library(purrr)
reduce(mlist,rbind)

使用示例数据:

> mlist <- list(matrix(1:9,nrow=3),matrix(1:9,nrow=3),matrix(1:9,nrow=3))
> mlist
[[1]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[[2]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
[[3]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

> reduce(mlist,rbind)
      [,1] [,2] [,3]
 [1,]    1    4    7
 [2,]    2    5    8
 [3,]    3    6    9
 [4,]    1    4    7
 [5,]    2    5    8
 [6,]    3    6    9
 [7,]    1    4    7
 [8,]    2    5    8
 [9,]    3    6    9

最新更新