R - Add a new column to a dataframe using matching values of another dataframe

前端 未结 3 710
南旧
南旧 2020-12-04 18:07

I am trying to fill in table1 with matching val2 values of table2

table1$New_val2 = table2[table2$pid==table1$pid,]$val2

But I get

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 18:59

    merge(table1, table2[, c("pid", "val2")], by="pid")

    Add in the all.x=TRUE argument in order to keep all of the pids in table1 that don't have matches in table2...

    You were on the right track. Here's a way using match...

    table1$val2 <- table2$val2[match(table1$pid, table2$pid)]

提交回复
热议问题