I am trying to merge two datasets in R. One of them contains baseline data for a cohort, and the other contains updated time-varying data for those same people over time. I need to merge the two into a long form dataset with one row for each year, but keep the non-time-varying variables (like sex or race, which don't get updated) the same in each row.
For example, with the datasets below, I would want 10 rows per ID number with marital_status and employment updated in each row, but sex remain fixed for each ID number. This seems like it should be relatively simple, but I can't find a way to merge them without leaving sex as NA in the years past baseline.
baseline <- data.frame(
ID = c(1:10),
year = 2000,
marital_status = (sample(0:1, 10, replace = TRUE)),
employment = (sample(0:1, 10, replace = TRUE)),
sex = (sample(c("M","F"), 10, replace = TRUE))
)
head(baseline)
time_varying <- data.frame(
ID = c(1:10),
year = rep(2001:2010, 10),
marital_status = (sample(0:1, 100, replace = TRUE)),
employment = (sample(0:1, 100, replace = TRUE))
)
head(time_varying)