Extract second subelement of every element in a list while ignoring NA's in sapply in R
Asked Answered
T

2

21

I'm trying to extract the second subelement of every element in a list while ignoring NAs in R. Here's a small example:

mylist <- list(a=c(6,7),b=NA,c=c(8,9))
sapply(mylist, "[[", 1)
sapply(mylist, "[[", 2) #receive error

Because element 'b' has only one subelement (NA), I receive the following error when trying to extract the second subelement:

Error in FUN(X[[2L]], ...) : subscript out of bounds

My goal is for the output to be: 7, NA, 9. In other words, I want to ignore and retain the NAs so that the output is the same length as the number of elements in the list. I would like the solution to be general enough to also be able to apply it to a different subelement, n, from each list.

Trave answered 1/10, 2013 at 15:28 Comment(0)
B
45

This should do what you want:

sapply(mylist,function(x) x[2])
Bosco answered 1/10, 2013 at 15:38 Comment(1)
Or more concisely, but equivalently, sapply(mylist,`[`,2) Fiducial
R
0

If the list just contains double vectors as in the example, I suggest:

purrr::map_dbl(mylist, 2, .default=NA)

Otherwise:

library(dplyr); purrr::map(mylist, 2, .default=NA) %>% unlist()
Renvoi answered 3/11, 2022 at 19:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.