用另一个数据集 (df2) 中的值替换 df1 中的值

Replace values in df1 with values from another dataset (df2)

这是问题:

** df1 ==> 你有一个数据集:

with df1$IDs 来自 1:100,(每个 ID 出现两次 df$visit),一个名为 df1$weight 的列和一个名为 df1$height[=23 的列=]

** df2==> 另一个数据集:

with df2$IDs 来自 1:50(每个 ID 出现两次 df$visit),以及名为 df2$weight.

的列

并且您想创建一个 THIRD 数据集,您将在其中拥有:

df1 中的数据集完全相同,但对于 df2 中存在的那些 ID,您将 df1$weight 替换为 df2$weight。显然是考虑到了访问。

你会怎么做?

谢谢!

我们可以加入

library(data.table)
df3 <- copy(df1)
setDT(df3)[df2, weight := i.weight, on = .(IDs)]

如果不止一栏,我们可以

setDT(df3)[df2, c('weight1', 'weight2') := .(i.weight1, i.weight2), on = .(IDs)]

如果有很多列,创建这些列名称的向量

nm1 <- names(df2)[1:5] # suppose if the first five column names wanted
nm2 <- paste0("i.", nm1) # for the corresponding column names from second data
setDT(df3)[df2, (nm1) := mget(nm2), on = .(IDs)]