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.
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
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With