Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 544
itpetersen Avatar asked Oct 01 '13 15:10

itpetersen


People also ask

How do you get all the first element of a list in R?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).


1 Answers

This should do what you want:

sapply(mylist,function(x) x[2])
like image 188
beginneR Avatar answered Sep 18 '22 22:09

beginneR