Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge all elements of list in R? [duplicate]

Tags:

I have a list containing data frames as its elements in R.

Example:

df1 <- data.frame("names"=c("John","Sam","Dave"),"age"=c(21,22,25)) df2 <- data.frame("names"=c("John","Sam"),"score"=c(22,25)) df3 <- data.frame("names"=c("John","Sam","Dave"),"country"=c("US","SA","NZ")) mylist <- list(df1,df2,df3) 

Is it possible to merge all the elements of mylist together without using a loop?

My desired output for this example is:

  names age score country 1  John  21    22      US 2   Sam  22    25      SA 

The list in this example has only three elements; however, I am looking for a solution that can handle an arbitrary number of elements.

like image 412
user2109248 Avatar asked Feb 25 '13 23:02

user2109248


People also ask

How do I merge all elements in a list 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 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.

How do I merge column data in R?

How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.

Which function is used to combine two lists 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.


1 Answers

You can use Reduce, one liner solution:

Reduce(merge,mylist)    names age score country 1  John  21    22      US 2   Sam  22    25      SA 
like image 124
agstudy Avatar answered Sep 29 '22 12:09

agstudy