简体   繁体   English

通过lapply过滤R中的对象列表

[英]Filtering List of Objects in R through lapply

How has a lapply function to be structured to pull out a specific objects by index? 如何构造一个lapply函数来通过索引提取特定对象? I have a List of Lists. 我有一份清单。 I now want to get every even 2nd, 4th and 5th element of the list and put them into a data frame. 我现在想要获得列表中每个偶数的第2,第4和第5个元素并将它们放入数据框中。 I thought the easiest way would be to use lapply and simply get the entries like this: 我认为最简单的方法是使用lapply并简单地获取如下条目:

list <-lapply(ll, function(x) { x[[2]]; x[[4]]; x[[5]] }

But that won't work as it seems. 但这似乎不会起作用。

this will work: 这将工作:

ll <- list(as.list(1:10),
           as.list(11:20),
           as.list(21:30))

library(magrittr)

output1 <- ll %>% sapply(function(x){c(x[[2]],x[[4]],x[[5]])}) %>% t %>% as.data.frame
# or with base syntax:
output2 <- as.data.frame(t(sapply(ll,function(x){c(x[[2]],x[[4]],x[[5]])})))
    #   V1 V2 V3
    # 1  2  4  5
    # 2 12 14 15
    # 3 22 24 25

your function is returning the result of the last operation, which in your case is ``x[[5]]`. 你的函数返回最后一个操作的结果,在你的情况下是``x [[5]]`。 the 2 operations you made before are lost. 你之前做的2个操作都会丢失。

Not sure what you want this data.frame to look like, but you can extract the 2, 4, and 5 elements with 不确定您希望这个data.frame看起来像什么,但您可以使用提取2个,4个和5个元素

lapply(ll, `[`, c(2,4,5))

and if you wanted to turn those into rows, you could do 如果你想将它们变成行,你可以这样做

do.call("rbind",lapply(ll, `[`, c(2,4,5)))

If you wanted them to become columns, you could do 如果你想让它们成为专栏,你可以做到

data.frame(sapply(ll, `[`, c(2,4,5)))

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

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