You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于公共ID用另一个data.table仅更新dt1的空值(NA)列

问题:基于公共ID仅更新data.table中为空的列

我需要用另一个data.table(dt2)基于公共id更新dt1的指定列,但仅当dt1中该列的值为空(NA)时才执行更新。

当前代码(会更新所有匹配ID的列)

dt1 <- data.table(
  "id" = c(1,2,3,4),
  "animal" = c("cat","cat","dog",NA)
)
dt2 <- data.table(
  "id" = c(3,4),
  "animal" = c("human being","duck")
)

dt1 <- dt1[dt2, on = c("id"),"animal" := .(i.animal)]

当前执行结果

id   animal
1:  1      cat
2:  2      cat
3:  3      human being
4:  4      duck

期望结果

id   animal
1:  1      cat
2:  2      cat
3:  3      dog
4:  4     duck

解决方案

可以在赋值语句中加入条件判断,仅当dt1的目标列值为NA时,才用dt2的对应值替换:

dt1[dt2, on = "id", animal := ifelse(is.na(x.animal), i.animal, x.animal)]

或者用更高效的data.table语法,先筛选出dt1中目标列为NA的行,再匹配dt2进行更新:

dt1[is.na(animal), animal := dt2[.SD, on = "id", i.animal]]

执行上述任意一段代码后,dt1就会得到期望的结果:仅id=4的行因为原animal值为NA被更新为"duck",id=3的行保留原有的"dog"。

内容的提问来源于stack exchange,提问作者Léon Ipdjian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:00:54