Nerd
Nerd

Reputation: 91

R: How to merge a new data frame to several other data frames in a list

I have several seperate data frames that I would like to keep separated because merging them together would create a very large element.

However, there are variables from another data frame that I would like to merge with all of them now.

Here is an example of what I would like to do:

df1 <- data.frame(ID1 = c(1:10), Var1 = rep(c(1,0),5))
df2 <- data.frame(ID1 = c(1:10), Var2 = c(21:30))

dfs <- Filter(function(x) is(x, "data.frame"), mget(ls()))

mergewith <- data.frame(ID1 = c(1:10), ID2 = c(41:50))

My goal is that df1 and df2 will look like this:

df1

   ID1 Var1 ID2
1    1    1  41
2    2    0  42
3    3    1  43
4    4    0  44
5    5    1  45
6    6    0  46
7    7    1  47
8    8    0  48
9    9    1  49
10  10    0  50

df2 

ID1 Var2 ID2
1    1   21  41
2    2   22  42
3    3   23  43
4    4   24  44
5    5   25  45
6    6   26  46
7    7   27  47
8    8   28  48
9    9   29  49
10  10   30  50

What I have tried so far is:

dat = lapply(dfs,function(x){
  merge(names(x), mergewith, by = "ID1");x})
list2env(dat,.GlobalEnv)

However, then I get the following message: "'by' must specify a uniquely valid column"

Is it possible to do this without using a loop?

Upvotes: 1

Views: 181

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

You can try Map

> Map(function(x, y) merge(x, y, by = "ID1"), dfs, list(mergewith))
[[1]]
   ID1 Var1 ID2
1    1    1  41
2    2    0  42
3    3    1  43
4    4    0  44
5    5    1  45
6    6    0  46
7    7    1  47
8    8    0  48
9    9    1  49
10  10    0  50

[[2]]
   ID1 Var2 ID2
1    1   21  41
2    2   22  42
3    3   23  43
4    4   24  44
5    5   25  45
6    6   26  46
7    7   27  47
8    8   28  48
9    9   29  49
10  10   30  50

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can use lapply to merge all the dataframes in dfs with mergewith. Use list2env to get the changed dataframes in the global environment.

list2env(lapply(dfs, function(x) merge(x, mergewith, by = 'ID1')), .GlobalEnv)

Upvotes: 1

Related Questions