I'm trying to accomplish something that allows me to merge two datasets with differing number of rows, match them on a common column and create NA values where there isn't matching data. For some reason, when I'm merging, the newly created data frame is auto filling values that should be NA and creating extra rows that I don't want. I'm trying to merge df_add (which has a total of 6 rows) into df_main (which has a total of 4 rows) and match the 2 on column "match_id" in df_main and "other_id" in df_add.
df_main <- data.frame (match_id = c("1", "1", "2", "2"),
index_date = c("2006-09-13", "2006-09-13", "2006-09-13", "2006-09-13"),
type = c("Good", "Good", "Bad", "Bad")
)
df_add <- data.frame (other_id = c("1", "1", "1", "2", "2", "2"),
measure_date = c("2005-01-01", "2005-03-13", "2005-04-19", "2005-06-22", "2005-09-29", "2005-11-03"),
wt = c(10, 11, 15, 60, 42, 33)
)
This code is the closest I've gotten so far - it gives me the 6 rows that I want with the NA values but it doesn't match "match_id" and "other_id"
merge(df_main, df_add, by = 0, all = TRUE)[-1]
This is what I want my final merged data set to look like with only a total of 6 rows:
df_goal <- data.frame (match_id = c("1", "1", "1", "2", "2", "2"),
index_date = c("2006-09-13", "2006-09-13", NA, "2006-09-13", "2006-09-13", NA),
type = c("Good", "Good", NA, "Bad", "Bad", NA),
measure_date = c("2005-01-01", "2005-03-13", "2005-04-19", "2005-06-22", "2005-09-29", "2005-11-03"),
wt = c(10, 11, 15, 60, 42, 33)
)
df_goal
Is there a way to accomplish this in r? Any help would be greatly appreciated!