如何用dplyr管道改写R中数据框列值替换的循环代码?
使用dplyr管道实现数据框值匹配替换
现有两个R数据框结构如下:
df1 <- data.frame(a=LETTERS[1:6], b=c("apple", "apple","dog", "red", "red","red")) df2 <- data.frame(col1=c("apple", "golf", "dog", "red"), col2=c("fruit", "sport","animal", "color"))
需求是将df1的b列值替换为df2中col1匹配对应的col2值,替代原有的for循环实现方式。
dplyr提供了两种简洁的管道实现方式:
方法一:使用left_join关联替换
通过左连接匹配对应值,再整理列名得到结果:
library(dplyr) output <- df1 %>% left_join(df2, by = c("b" = "col1")) %>% select(a, b = col2)
方法二:使用recode批量替换
利用命名向量批量映射替换b列的值:
library(dplyr) output <- df1 %>% mutate(b = recode(b, !!!set_names(df2$col2, df2$col1)))
两种方式都能高效得到目标结果,且比for循环更简洁易读,数据量较大时性能优势更明显。
内容的提问来源于stack exchange,提问作者Mathica
相关产品推荐
相关产品推荐

