1
votes

I Have two dataframes DF1 and DF2.

DF1    Names  B.P   Age Sex
        Ted    120  23   M
        Sed    110   24  F
        Med    123    23  M

DF2   Names  Income
       Ted    1000
        Sed    2000
        Fed    3000
        Med    1000

DF1 contains three variables against every Participant Name. (DF1$Names). All i want is to add the column (DF2$Income) from DF2 to DF1 But only Income data of Ted Sed and Med should be added. I mean only that data from new column should be added coresponding to the Names in DF1. I want following output.

DF3



Names   B.P Age   Sex   Income
        Ted    120  23   M    1000
        Sed    110   24  F    2000
        Med    123    23  M   1000

Dput:

df1 <- structure(list(Names = c("Ted", "Sed", "Med"), B.P = c(120, 110, 
123), Age = c(23, 24, 23), Sex = c("M", "F", "M")), class = "data.frame", row.names = c(NA, 
-3L))

df2 <- structure(list(Names = c("Ted", "Sed", "Fed", "Med"), Income = c(1000, 
2000, 3000, 1000)), class = "data.frame", row.names = c(NA, -4L
))
2

2 Answers

3
votes

Here's a dplyr solution:

library(dplyr)
DF3 <- left_join(df1, df2, by = "Names")

Here's a data.table solution:

library(data.table)
Df3 <- merge(df1, df2, by = "Names")
0
votes

In your case, since the there is a common column, the base R merge is enough:

merge(df1,df2)
  Names B.P Age Sex Income
1   Med 123  23   M   1000
2   Sed 110  24   F   2000
3   Ted 120  23   M   1000