Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge more than two lists in R

Tags:

merge

r

Basically, I want to merge multiple lists in to a single list. All lists have same structure. Here is one example:

file1=list(A=1,B=2)
file2=list(A=2,B=3)
file3=list(A=3,B=4)

I know mapply() or Map() works.

> mapply(c, file1, file2, file3, SIMPLIFY=FALSE)
[[1]]
[1] 1 2 3

[[2]]
[1] 2 3 4

But the problem is that I actually have 500 lists, well, I can sure copy and paste object names 500 times. However, I'd like to learn how to do it efficiently. I have a vector containing names of each 500 lists, like this,

lsNames=c("file1","file2","file3")

but I have to no idea how to start, I appreciate any help, thanks.

like image 414
Christopher B. L Avatar asked Sep 25 '15 13:09

Christopher B. L


People also ask

How do I combine multiple lists into one in R?

combine. lists is an R function developped combine/append two lists, with special attention to dimensions present in both. combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.

How do I combine multiple data frames into one in R?

To join two data frames (datasets) vertically, use the rbind function. The two data frames must have the same variables, but they do not have to be in the same order. If data frameA has variables that data frameB does not, then either: Delete the extra variables in data frameA or.

How do I join a list in R?

To join two or more lists in R programming, call c() function and pass the lists to join, as arguments, in function call.

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

If we want to merge more than two dataframes we can use cbind() function and pass the resultant cbind() variable into as. list() function to convert it into list .


Video Answer


1 Answers

Here's an alternative that works by constructing and then evaluating the same call to mapply() shown in the OP:

do.call(mapply, c(FUN=c, sapply(lsNames, as.symbol), SIMPLIFY=FALSE))
# $A
# file1 file2 file3 
#     1     2     3 
# 
# $B
# file1 file2 file3 
#     2     3     4 
like image 181
Josh O'Brien Avatar answered Nov 12 '22 15:11

Josh O'Brien