Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge data.frames between two lists by one single column

Here an example of my two lists and data.frames:

df1 = data.frame(a = c(1,2,3,4,5,6,7))
df2 = data.frame(a = c(111,112,113,114))

lst1 = list(df1, df2)

df3 = data.frame(a = c(1,2,3,4,5,6,7,8,9,10), b = c(10,11,12,13,14,15,16,17,18,19))
df4 = data.frame(a = c(111,112,113,114,115,116,117,118,119), b = c(22,23,24,25,26,27,28,29,30))

lst2 = list(df3, df4)

I need to merge lst1 with lst2 by column a in order to have df1 merged with df3 and df2 with df4.

Here my desired output:

> output_lst
[[1]]
   a  b
   1 10
   2 11
   3 12
   4 13
   5 14
   6 15
   7 16

[[2]]
    a  b
1 111 22
2 112 23
3 113 24
4 114 25

I tried a lot with both lapply and Map but without results. Thanks

like image 858
aaaaa Avatar asked Mar 16 '17 22:03

aaaaa


2 Answers

It's just:

Map(merge, lst1, lst2)
#or more explicitly
Map(merge, lst1, lst2, by="a")

Map is basically a glorified loop doing:

merge(lst1[[1]], lst2[[1]], by="a")
#and
merge(lst1[[2]], lst2[[2]], by="a")
like image 132
thelatemail Avatar answered Oct 20 '22 21:10

thelatemail


Try this:

sapply(seq_len(length(lst1)), 
       function(i) list(merge(lst1[[i]], lst2[[i]], by = "a", all.x=TRUE)))

# [[1]]
  # a  b
# 1 1 10
# 2 2 11
# 3 3 12
# 4 4 13
# 5 5 14
# 6 6 15
# 7 7 16

# [[2]]
    # a  b
# 1 111 22
# 2 112 23
# 3 113 24
# 4 114 25
like image 1
989 Avatar answered Oct 20 '22 21:10

989