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
相关产品推荐
相关产品推荐

