简体   繁体   中英

Filtering List of Objects in R through lapply

How has a lapply function to be structured to pull out a specific objects by index? 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. I thought the easiest way would be to use lapply and simply get the entries like this:

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]]`. the 2 operations you made before are lost.

Not sure what you want this data.frame to look like, but you can extract the 2, 4, and 5 elements with

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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