2

In R, I have unsuccessfully tried to merge to dataframes of different length which are matched by a column called id. Do anyone know how to address this?

Input:

df1:

id  group
1   x
2   y
3   x

df2:

id  day
1   0   
1   1   
1   2
2   0 
2   1
2   2
3   0 
3   1
3   2

Desired output (df2 with an added group column based on df1):

id  day   group
1   0     x
1   1     x
1   2     x
2   0     y
2   1     y
2   2     y
3   0     x
3   1     x
3   2     x
vincentleroy
  • 35
  • 1
  • 5

3 Answers3

2

Using left_join from dplyr package:

library(dplyr)

data <- left_join(df1,df2, by="id")

Ariel
  • 395
  • 1
  • 14
1

Use a left_join

library(dplyr)
df_joined<- df2 %>%
   left_join(df1, by="id")
Joe Erinjeri
  • 1,200
  • 1
  • 7
  • 15
1

I think the simple merge function with specification of "id" variable works well

merge(df1,df2,by="id")
Yacine Hajji
  • 1,124
  • 1
  • 3
  • 20