从R中的列表中提取向量而不进行循环

时间:2015-07-13 20:46:58

标签: r

这可能是一个非常简单的问题,但是我用谷歌搜索了几个小时而没有令人满意的答案。让我们假设我有一个如下列表:

theList <- list(c("de", "labore", "solis"), c("sapiento", "post", "eventum"), c("sursum", "corda"))

> theList
[[1]]
[1] "de"     "labore" "solis" 

[[2]]
[1] "sapiento" "post"     "eventum" 

[[3]]
[1] "sursum" "corda" 

如果我想打印组成列表的所有向量,我会想到像

这样的东西
for(i in 1:length(theList)) {
  print(theList[[i]])
}

[1] "de"     "labore" "solis" 
[1] "sapiento" "post"     "eventum" 
[1] "sursum" "corda" 

然而,必须有一个更优雅的解决方案,可能使用申请家庭的一些成员......

1 个答案:

答案 0 :(得分:-1)

I think I got an answer after doing some more googling and experimenting...

extract <- function(m) {
  sapply(seq_along(m), function(x) m[[x]])
}

> extract(theList)
[[1]]
[1] "de"     "labore" "solis" 

[[2]]
[1] "sapiento" "post"     "eventum" 

[[3]]
[1] "sursum" "corda" 

So it would be a matter of performing the desired operation (e.g. printing) on the result from the sapply