简体   繁体   English

从R列表中的矩阵中提取行

[英]Extract row from a matrix in a list in R

I'm trying to extract rows from all the matrices in a list in R. Is there an easy way to do this other than looping? 我正在尝试从R列表中的所有矩阵中提取行。除了循环之外,还有一种简单的方法吗? For eg, 例如

set.seed(123)
list1 <- list(replicate(4,rnorm(2)))
rep(list1,3)

This code generates the following list: 此代码生成以下列表:

[[1]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

[[2]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

[[3]]
           [,1]       [,2]      [,3]       [,4]
[1,] -0.5604756 1.55870831 0.1292877  0.4609162
[2,] -0.2301775 0.07050839 1.7150650 -1.2650612

Now I want to extract 2nd row of all the matrices in this list and store it in another matrix or list. 现在,我要提取此列表中所有矩阵的第二行,并将其存储在另一个矩阵或列表中。 Is there a way to do this without looping? 有没有办法做到这一点而不循环?

Thanks 谢谢

Or like this? 还是这样?

set.seed(123)
list1 <- list(replicate(4,rnorm(2)))
l<-rep(list1,3)
lapply(l,function(x) x[2,])
matrix(unlist(lapply(x,function (x) { x[2,]})),nrow=length(x), byrow=T)

           [,1]      [,2]       [,3]       [,4]
[1,] -0.2372892 0.8751748 -0.5452381 -0.1484494
[2,] -0.2372892 0.8751748 -0.5452381 -0.1484494
[3,] -0.2372892 0.8751748 -0.5452381 -0.1484494

This extracts the rows with lapply and puts them together with rbind . 这将用lapply提取行,并将它们与rbind放在一起。

x = rep(list1,3)
do.call( rbind, lapply(x,'[',2,) )

The plyr package is another option plyr软件包是另一种选择

library(plyr)
laply(x,function(y) y[2,])

The ?"[" help page is enlightening. ?"["帮助页面很有启发性。 After reading it, I realized the very short, simple code below also works. 阅读后,我意识到下面的简短代码也可以使用。

laply(x,'[',2,TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM