【问题标题】:str_replace_all in for loop [closed]for循环中的str_replace_all [关闭]
【发布时间】:2021-07-21 14:06:21
【问题描述】:

我想用某些替换词替换某些词。 我做了一个 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"))



for(i in 1:nrow(wordmatch)) {
  text_output <- text %>% 
    str_replace_all(example, fixed(wordmatch$word[i]), wordmatch$replacement[i])
  return(text_output)
  
}

print(text_output)

输出为:"c(\"here are some examples\", \"and question i ask\")"

questions 正确地变成了 question 但是 examples 应该变成 example

【问题讨论】:

  • 循环的每次迭代都会覆盖text_output。这就是为什么它似乎只进行了最后一次替换。

标签: r for-loop str-replace stringr


【解决方案1】:

使用purrr

library(purrr)
text <- data.frame(
  tekstid = c(1,2),
  example = c("here are some examples", "and questions i ask")
)

wordmatch <- c("examples" = "example",
               "questions" = "question")

text$example <- data.frame(example = matrix(unlist(map(text[,2],
                                                       str_replace_all,
                                                       wordmatch)),
                                            ncol = 1))

输出:

  tekstid               example
1       1 here are some example
2       2    and question i ask

【讨论】:

猜你喜欢
  • 2021-08-14
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2017-02-19
  • 2016-08-26
相关资源
最近更新 更多