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.

oercim
  • 1,808
  • 2
  • 17
  • 34
  • 2
    What did you search? What did you find? What did you try? –  Feb 25 '16 at 21:11
  • Check https://stackoverflow.com/questions/8091303/simultaneously-merge-multiple-data-frames-in-a-list – talat Feb 25 '16 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`. – coffeinjunky Feb 25 '16 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` – inscaven Feb 26 '16 at 09:59

1 Answers1

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.

dmontaner
  • 2,076
  • 1
  • 14
  • 17