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

如何匹配两个数据框指定列的相同值行并补全对应NA值

解决方法

方法1:使用dplyr包(最简洁)

rows_patch 函数天生适配该场景,会自动以指定列为匹配键,用第二个数据框的非NA值覆盖第一个数据框的对应缺失值,同时保留第一个数据框的所有行和原有顺序:

library(dplyr)
# 构造示例数据
df1 <- data.frame(
  cpf = c(21, 32, 43, 54, 65),
  x = rep(NA_integer_, 5),
  y = rep(NA_integer_, 5)
)
df2 <- data.frame(
  cpf = c(54, 0, 65, 0, 0),
  x = c(5, NA, 3, NA, NA),
  y = c(10, NA, 2, NA, NA)
)
# 执行更新,指定匹配键为cpf
df3 <- rows_patch(df1, df2, by = "cpf")

输出结果完全符合预期:

> df3
  cpf  x  y
1  21 NA NA
2  32 NA NA
3  43 NA NA
4  54  5 10
5  65  3  2

方法2:Base R实现(无需额外安装包)

如果不想依赖第三方包,可以用匹配索引+遍历更新的方式实现:

# 找到df1中cpf在df2中存在的行的匹配索引
match_idx <- match(df1$cpf, df2$cpf)
# 遍历需要更新的列,用df2的非NA值替换
for (col in c("x", "y")) {
  df1[!is.na(match_idx), col] <- df2[na.omit(match_idx), col]
}
df3 <- df1

实现效果和dplyr方法完全一致。

内容的提问来源于stack exchange,提问作者Marcos O. C. Alves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 14:15:05