How to combine data frames stored in a list in R?


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

For Example, if we have a list called LIST that contains some data frames then we can combine those data frames by using the below command −

Reduce(full_join,LIST)

Check out the Example given below to understand the Output of this command.

Example

Following snippet creates a sample data frame −

df1<-data.frame(x=rpois(10,2),y=rpois(10,5),z=rpois(10,2))
df2<-data.frame(z=rpois(10,2),a=rpois(10,8),b=rpois(10,3))
df3<-data.frame(b=rpois(10,5),z=rpois(10,8),c=rpois(10,5))
List<-list(df1,df2,df3)
List

The following dataframe is created

[[1]]
   x  y z
 1 2  5 2
 2 1  3 0
 3 3  7 0
 4 6  3 2
 5 3  5 3
 6 0 10 0
 7 3  4 0
 8 1  5 1
 9 3  3 1
10 1  3 1
[[2]]
   z  a b
 1 0  7 3
 2 3  8 6
 3 2  9 4
 4 0  7 3
 5 6 14 1
 6 1  6 3
 7 0  7 2
 8 3  7 4
 9 2  6 3
10 1  9 3
[[3]]
  b   z c
 1 4  6 5
 2 5  9 4
 3 7  9 4
 4 4 10 10
 5 3  2 3
 6 7  8 7
 7 3  4 2
 8 5  7 9
 9 6  8 7
10 5 10 9

To load dplyr package and combine data frames stored in List on the above created data frame, add the following code to the above snippet −

df1<-data.frame(x=rpois(10,2),y=rpois(10,5),z=rpois(10,2))
df2<-data.frame(z=rpois(10,2),a=rpois(10,8),b=rpois(10,3))
df3<-data.frame(b=rpois(10,5),z=rpois(10,8),c=rpois(10,5))
List<-list(df1,df2,df3)
List
library(dplyr)
Reduce(full_join,List)
Joining, by = "z"
Joining, by = c("z", "b")

Output

If you execute all the above given snippets as a single program, it generates the following Output −

    x  y  z  a b  c
 1  2  5  2  9 4 NA
 2  2  5  2  6 3  3
 3  1  3  0  7 3 NA
 4  1  3  0  7 3 NA
 5  1  3  0  7 2 NA
 6  3  7  0  7 3 NA
 7  3  7  0  7 3 NA
 8  3  7  0  7 2 NA
 9  6  3  2  9 4 NA
10  6  3  2  6 3  3
11  3  5  3  8 6 NA
12  3  5  3  7 4 NA
13  0 10  0  7 3 NA
14  0 10  0  7 3 NA
15  0 10  0  7 2 NA
16  3  4  0  7 3 NA
17  3  4  0  7 3 NA
18  3  4  0  7 2 NA
19  1  5  1  6 3 NA
20  1  5  1  9 3 NA
21  3  3  1  6 3 NA
22  3  3  1  9 3 NA
23  1  3  1  6 3 NA
24  1  3  1  9 3 NA
25 NA NA  6 14 1 NA
26 NA NA  6 NA 4  5
27 NA NA  9 NA 5  4
28 NA NA  9 NA 7  4
29 NA NA 10 NA 4 10
30 NA NA  8 NA 7  7
31 NA NA  4 NA 3  2
32 NA NA  7 NA 5  9
33 NA NA  8 NA 6  7
34 NA NA 10 NA 5  9

Updated on: 05-Nov-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements