使用purrr::map重写向量,如for循环

如何仅使用 purrr::map 返回示例的 for 循环的结果:

vct_string <- c("old ccar","new carr", "house", "oold house")

df_correction <- data.frame(
  pattern  = c("ccar", "carr", "oold"),
  replacement = c("car", "car", "old"),
  stringsAsFactors = FALSE
)

for(i in 1:nrow(df_correction)){
  vct_string <- pmap(df_correction, gsub, x = vct_string)[[i]]
}

> vct_string
[1] "old car"   "new car"   "house"     "old house"

回答

实际上,您不需要任何ReduceMap功能。只需使用str_replace_all其矢量化

library(stringr)
str_replace_all(vct_string, set_names(df_correction$replacement, df_correction$pattern))

[1] "old car"   "new car"   "house"     "old house"


以上是使用purrr::map重写向量,如for循环的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>