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

在R中通过ID匹配将数据框weight值填充至另一数据框NA

用匹配ID填充DataFrame的缺失Weight值

问题背景

我有两个DataFrame:

  • df1包含30个唯一ID,weight列存在NA值
  • df2仅包含8个唯一ID,weight数据完整

需求:忽略日期维度,根据匹配的ID,将df2中的weight值填充到df1对应ID的所有weight列NA位置。

数据示例

df1

id            date      calories    weight
1503960366 2016-04-12     1985        NA
1503960366 2016-04-13     1797        NA
...(其余内容省略)

df2

id            date      calories    weight
1503960366 2016-05-02     2004      52.6
1927972279 2016-04-13     2151     133.5
...(其余内容省略)

尝试过的代码

df3 <- df1 %>%
  mutate(weight = ifelse(id == df2$id,
                            df2$weight, weight))

df3 <- df1 %>%
  select(.)
  mutate(
    weight = ifelse(
      id == df2$id ,
      paste(df2$weight_kg), NA_character_) )

期望效果

id            date      calories    weight
1503960366 2016-04-12     1985        52.6
1503960366 2016-04-13     1797        52.6
...(其余内容省略)

解决方案

之前的代码问题在于直接用id == df2$id会因两个DataFrame行数不匹配,导致向量长度不一致,无法正确匹配。以下是两种可靠的解决方法:

方法1:使用dplyr的left_join + coalesce

先从df2提取唯一的ID-weight映射,再和df1关联,最后用coalesce替换NA值:

library(dplyr)

# 从df2提取每个ID对应的唯一weight值(假设每个ID在df2中仅对应一个weight)
weight_map <- df2 %>%
  distinct(id, .keep_all = TRUE) %>%
  select(id, weight_df2 = weight)

# 关联并填充缺失值
df3 <- df1 %>%
  left_join(weight_map, by = "id") %>%
  mutate(weight = coalesce(weight, weight_df2)) %>%
  select(-weight_df2) # 移除临时辅助列

方法2:使用match函数直接匹配

如果不想用关联操作,可以用match定位每个df1的ID在df2中的位置,提取对应weight值:

df3 <- df1 %>%
  mutate(weight = ifelse(is.na(weight), 
                         df2$weight[match(id, df2$id)], 
                         weight))

注:若df2中同一个ID对应多个weight值,match会取第一个出现的值,建议先对df2去重,确保每个ID对应唯一weight。


内容的提问来源于stack exchange,提问作者Cladney Restauro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 09:13:27