I have two dataframes (df1, df2). I want to fill in the AGE and SEX values from df1 to df2 conditioned on having the same ID between the two. I tried several ways using for-loop
Try merge(df1, df2, by = "id")
. This will merge your two data frames together. If your example is a good representation of your actual data, then you might want to go ahead and drop the age and sex columns from df2 before you merge.
df2$AGE <- NULL
df2$SEX <- NULL
df3 <- merge(df1, df2, by = "id")
If you need to keep rows from df2 even when you don't have a matching id in df1, then you do this:
df2 <- subset(df2, select = -c(AGE,SEX) )
df3 <- merge(df1, df2, by = "id", all.y = TRUE)
You can learn more about merge
(or any r function) by typing ?merge()
in your r console.