0

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.

4
  • 2
    What did you search? What did you find? What did you try? Commented Feb 25, 2016 at 21:11
  • Check stackoverflow.com/questions/8091303/… Commented Feb 25, 2016 at 21:20
  • Your example, in which all dataframes contain only one column called x besides the id, it looks like you don't actually need to merge, just to bind the rows together (unless you want to keep observations with no value in x as NA). Look at rbind_all. Commented Feb 25, 2016 at 21:59
  • using dplyr library you can do just df %>% left_join(df1) %>% left_join(df2) or maybe bind_rows(df1, df2) if you dont need rows where x is NA Commented Feb 26, 2016 at 9:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.