R语言for循环调用str_replace_all仅最后一次替换生效如何解决
问题原因
- 每次循环都基于原始的
text数据执行替换,没有继承上一轮循环的修改结果,所以之前的替换操作都会被最后一轮的操作覆盖 - for循环中错误使用了
return()语句,该语句仅用于函数体内返回结果,普通脚本中使用会直接终止程序运行。即便删除return(),也会因为第一条问题导致仅最后一次替换生效 str_replace_all()直接作用于数据框时写法错误,没有搭配mutate()修改指定列,导致最终输出的是向量而非保留原有结构的数据框
修正后代码(for循环版本)
library(dplyr) library(stringr) text <- data.frame( tekstid = c(1,2), example = c("here are some examples", "and questions i ask") ) wordmatch <- data.frame( word = c("examples", "questions"), replacement = c("example", "question")) # 初始化输出变量为原始数据,后续修改都基于该变量迭代 text_output <- text for(i in 1:nrow(wordmatch)) { text_output <- text_output %>% mutate(example = str_replace_all(example, fixed(wordmatch$word[i]), wordmatch$replacement[i])) } print(text_output)
更简便的批量替换方案(无需for循环)
str_replace_all()原生支持传入命名向量实现多对多批量替换,不需要手动编写循环:
# 构造替换用命名向量,元素名为待替换词,元素值为目标替换内容 replace_vec <- setNames(wordmatch$replacement, wordmatch$word) text_output <- text %>% mutate(example = str_replace_all(example, replace_vec))
运行后输出结果:
tekstid example 1 1 here are some example 2 2 and question i ask
内容的提问来源于stack exchange,提问作者Nina van Bruggen
相关产品推荐
相关产品推荐

