Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to flatten a list of list while only keeping the 1st element in each sublist

Tags:

r

Consider the command that creates a list of list as follows:

myList <- list(a = list(1:5), b = "Z", c = NA)

This creates something like:

 $a
 $a[[1]]
 [1] 1 2 3 4 5

 $b
 [1] "Z"

 $c
 [1] NA

Now when I do unlist to this,

unlist(myList, recursive = FALSE)

I get

 $a
 [1] 1 2 3 4 5

 $b
 [1] "Z"

 $c
 [1] NA

whereas what I am actually looking for is the first element from each sublist , i.e.

 1
 "Z"
 NA

Loops are very slow. No loops please.

like image 906
Vinayak Agarwal Avatar asked Dec 04 '22 01:12

Vinayak Agarwal


2 Answers

I guess it depends on what you consider to be a loop. e.g. I'd call this a loop, but maybe it's okay for you?

> sapply(unlist(myList, recursive=FALSE), "[", 1)
  a   b   c 
"1" "Z"  NA 

If you do not want the names

> sapply(unlist(myList, recursive=FALSE, use.names=FALSE), "[", 1)
[1] "1" "Z" NA 
like image 126
GSee Avatar answered Jan 12 '23 17:01

GSee


@GSee's solution is perhaps the most common one that comes to mind, but there is also the rapply() function ("recursive lapply()") that achieves what you're looking for:

rapply(myList, function(x) x[1], how = "unlist")
#   a   b   c 
# "1" "Z"  NA 
unname(rapply(myList, function(x) x[1], how = "unlist"))
# [1] "1" "Z" NA
like image 22
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 12 '23 18:01

A5C1D2H2I1M1N2O1R2T1