0

Is it possible to fill a column based a common column values between 2 dataframes?

For example the first df1 has this data:

group, num
12, 0
19, 0
43, 1

and the second df2:

group
11
11
11
12
12
12
12
24
24
25
43
43

and the output I want to have is this:

 group, out
    11
    11
    11
    12, 0
    12, 0
    12, 0
    12, 0
    24
    24
    25
    43, 1
    43, 1

If the group from df1 value exist in df2 group column then fill the value of column num from df1 in the new df otherwise leave empty the cell.

Jake
  • 95
  • 2
  • 13

1 Answers1

0

left.join from dplyr library is all you need. What it does is to keep all the values from the first data.frame and join them when possible with the second data.frame based on a given column.

library (dplyr)
df1 <- data.frame("group"=c(12,19,43), "num"=c(0,0,1))
print (df1)
  group num
1    12   0
2    19   0
3    43   1

df2 <- data.frame("group"=c(11,11,11,12,12,12,12,24,24,25,43,43))
print (df2)
   group
1     11
2     11
3     11
4     12
5     12
6     12
7     12
8     24
9     24
10    25
11    43
12    43

df3 <- left_join(df2, df1, by = "group")
print (df3)
   group num
1     11  NA
2     11  NA
3     11  NA
4     12   0
5     12   0
6     12   0
7     12   0
8     24  NA
9     24  NA
10    25  NA
11    43   1
12    43   1
maria
  • 63
  • 6