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

R语言根据dataframe的father与id列匹配关系修改pop列值的方法

实现思路

先构建father字段到对应pop值的映射关系,再用id字段匹配该映射,匹配成功则替换原pop值,匹配失败保留原值即可。


方案1:dplyr实现(代码易读性高)

library(dplyr)

# 构建father-pop唯一映射表
father_pop_map <- df %>% 
  distinct(father, .keep_all = TRUE) %>% 
  select(father, pop)

# 匹配替换pop值
df_result <- df %>% 
  left_join(father_pop_map, by = c("id" = "father"), suffix = c("_orig", "_match")) %>% 
  mutate(pop = coalesce(pop_match, pop_orig)) %>% 
  select(father, id, pop)

运行后df_result输出和你期望的结果完全一致:

father id pop
1      A  C val
2      B  E ref
3      B  F ref
4      C  G val
5      D  H val

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

# 构建命名向量作为映射
pop_map <- setNames(df$pop, df$father)
# 匹配替换
matched_pop <- pop_map[df$id]
df$pop <- ifelse(!is.na(matched_pop), matched_pop, df$pop)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:06:07