Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge lists with identical column names to get their union

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?

like image 233
N08 Avatar asked Nov 08 '17 12:11

N08


2 Answers

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
like image 56
akrun Avatar answered Nov 15 '22 05:11

akrun


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
like image 3
lmo Avatar answered Nov 15 '22 07:11

lmo