如何用基础R语言按条件填充data.frame列,无匹配设为LC?
基础R解决方案
方法1:使用merge()函数
通过关联两个数据框匹配对应值,再填充缺失项,最后恢复原数据顺序:
# 模拟示例数据 df1 <- data.frame( scientific_name = c("Panthera leo", "Gorilla gorilla", "Loxodonta africana"), threat_status = c("VU", "CR", "EN"), stringsAsFactors = FALSE ) df2 <- data.frame( scientific_name = c("Panthera leo", "Pongo abelii", "Gorilla gorilla", "Homo sapiens"), threat_status = NA, stringsAsFactors = FALSE ) # 合并数据并填充值 merged_data <- merge(df2, df1, by = "scientific_name", all.x = TRUE, suffixes = c("", "_ref")) merged_data$threat_status <- ifelse(is.na(merged_data$threat_status_ref), "LC", merged_data$threat_status_ref) # 保留目标列并恢复df2原始行顺序 df2_final <- merged_data[match(df2$scientific_name, merged_data$scientific_name), c("scientific_name", "threat_status")] # 查看结果 print(df2_final)
all.x = TRUE确保保留df2的所有条目ifelse判断:匹配不到df1数据时填充"LC",否则用df1的对应状态match()用来还原df2的原始行顺序,避免合并后顺序混乱
方法2:使用match()直接赋值
更简洁的原地修改方式,无需额外合并数据框:
# 模拟示例数据同上 df2$threat_status <- df1$threat_status[match(df2$scientific_name, df1$scientific_name)] # 将未匹配到的NA替换为"LC" df2$threat_status[is.na(df2$threat_status)] <- "LC" # 查看结果 print(df2)
match()返回df2每条记录在df1中的位置索引,无匹配项返回NA- 直接用索引提取df1的状态值赋值给df2,最后批量替换剩余NA为"LC"
内容的提问来源于stack exchange,提问作者Fabiula Arantes
相关产品推荐
相关产品推荐

