I am trying to merge two data frames by group id. However, both data frames are not of the same length and some elements of certain groups are missing in the second data frame. In the merged file, the missing elements of a certain group should be NAs.
The data looks something like this
df1 <- data.frame(id = c(1,1,1,2,3,3,4), x = c("a", "b", "c", "d", "e", "f", "g"))
df2 <- data.frame(id = c(1,1,2,3,4), y = c("A", "B", "D", "E", "G"))
Ideally, the result would look like this:
id x y
1 a A
1 b B
1 c <NA>
2 d D
3 e E
3 f <NA>
4 g G
It would be great if the code worked for additional columns that also correspond to the same group ids but may miss elements at different places.
I have tried full_join
and merge
so far but without success, as they just repreat the y values instead of introducing na's.
I know there are similar questions out there, but I have found none that solves this problem. Any help is appreciated.