1

I have a data frame, say df1, that looks something like this:

    ID     
1   ABC
2   ABD
3   ABE
4   ABF
5   ABG
.
. 

and I want to join a data frame to df1 that has less rows than df1, like this one:

    ID     Value1    Value 2
1   ABC      5         6
2   ABD      1         2
3   ABG      4         4
.
.

so that the final product looks like this:

    ID     Value1    Value 2
1   ABC      5         6
2   ABD      1         2
3   ABE      NA        NA
4   ABF      NA        NA 
5   ABG      4         4
.
.

How can I do about doing this? Thanks in advance.

2 Answers2

1

Data

df1 = data.frame(ID =  c("ABC", "ABD", "ABE", "ABF", "ABG"))
df2 = data.frame(ID =  c("ABC", "ABD", "ABG"), Value1 = c(5, 4, 1), Value2 = c(6, 2, 4))

Solution

merge(df1, df2, all.x = TRUE)

#   ID Value1 Value2
#1 ABC      5      6
#2 ABD      4      2
#3 ABE     NA     NA
#4 ABF     NA     NA
#5 ABG      1      4

Explanation

Reading ?merge, we see that the logical argument all.x does exactly what you wanted:

all.x

logical; if TRUE, then extra rows will be added to the output, one for each row in x that has no matching row in y. These rows will have NAs in those columns that are usually filled with values from y. The default is FALSE, so that only rows with data from both x and y are included in the output.

catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43
0

Try merge(df1,df2,by = "ID", all = TRUE)

Víctor Cortés
  • 473
  • 4
  • 9