oercim
oercim

Reputation: 1848

Merging multiple data frames in a loop

I have such a data frame(df) with ID's

ID
1
2
3
4
5
6

I have such data frames df1 and df2:

df1:

ID  x
3   656
5   678

df2:

ID x
1  45
2  954
6  1245

I want to merge df1 and df2 onto df. The resulting data frame will be:

ID  x
1   45
2   954
3   656
4   NA
5   678
6   1245

In my real problem, I have a lot of data frames to merge with df(df also have a lot of more ID's). I want to this merging procedure in a loop. How can I do that in R? I will bevery glad for any help. Thanks a lot.

Upvotes: 0

Views: 1894

Answers (1)

dmontaner
dmontaner

Reputation: 2165

You can try something like this:

create the 'x' column with all NA values in your first data.frame

df[,"x"] <- NA

use your ID column to name the rows of your first data.frame

rownames (df) <- df$ID

and then use this rownames to replace the 'x' column just in the desired rows depending of each of your other datasets

df[df1$ID, "x"] <- df1$x

df[df2$ID, "x"] <- df2$x

This will keep the NA values in the 'x' column as in your example.

Upvotes: 1

Related Questions