Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Two Lists in R

Tags:

list

dataframe

r

I have two lists

first = list(a = 1, b = 2, c = 3) second = list(a = 2, b = 3, c = 4) 

I want to merge these two lists so the final product is

$a [1] 1 2  $b [1] 2 3  $c [1] 3 4 

Is there a simple function to do this?

like image 623
Michael Avatar asked Mar 01 '12 16:03

Michael


People also ask

How do I join multiple lists in R?

Combine lists in R Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.

How do I combine two arrays in R?

The row binding operation in R creates a matrix that contains the number of rows specified. SImilarly, n number of arrays can be created. The cbind() operation is then applied which takes as arguments the array vectors. It creates a combined matrix where the merging takes place using columns.

How do I merge a list of data frames in R?

To combine data frames stored in a list in R, we can use full_join function of dplyr package inside Reduce function.


2 Answers

If lists always have the same structure, as in the example, then a simpler solution is

mapply(c, first, second, SIMPLIFY=FALSE) 
like image 145
Andrei Avatar answered Oct 13 '22 04:10

Andrei


This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.

appendList <- function (x, val)  {     stopifnot(is.list(x), is.list(val))     xnames <- names(x)     for (v in names(val)) {         x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))              appendList(x[[v]], val[[v]])         else c(x[[v]], val[[v]])     }     x }  > appendList(first,second) $a [1] 1 2  $b [1] 2 3  $c [1] 3 4 
like image 37
IRTFM Avatar answered Oct 13 '22 05:10

IRTFM