Say I have N lists that all have the same column names. I want to merge these such that I get a resulting list with same columns, but now containing entries from all N list. Here is a MWE showing what I want:
ls<-list()
ls[[1]]<-list("a"=1,
"b"=2)
ls[[2]]<-list("a"=3,
"b"=4)
#how to write a one-liner that produces lsTotal, which is the union of ls[[1]] and ls[[2]]?
lsTotal<-list("a"=c(1,3),
"b"=c(2,4))
I found this thread, from which I can use Map(c, ls[[1]], ls[[2]])
. However, writing it out is tedious if ls
is very long. Is there a shortcut?
One option is tidyverse
library(purrr)
library(dplyr)
transpose(ls) %>%
map(unlist)
Or use Map
with do.call
do.call(Map, c(f=c, ls))
#$a
#[1] 1 3
#$b
#[1] 2 4
Here is a simple two-liner with unlist
and split
.
# get a named vector
tmp <- unlist(ls)
# split on the names
split(unname(tmp), names(tmp))
$a
[1] 1 3
$b
[1] 2 4
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