filling in columns with matching IDs from two dataframes in R

后端 未结 2 1675
刺人心
刺人心 2021-02-09 15:45

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

2条回答
  •  自闭症患者
    2021-02-09 16:11

    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.

提交回复
热议问题