[英]Use purrr::map to rewrite a vector as in for loop
如何使用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"
你必須遞歸地修改你的向量,所以在我看來,這是使用 reduce 系列 function 的經典案例。 所以這樣做,你必須將你的向量傳遞給purrr::reduce
的.init
參數以獲得所需的 output
purrr::reduce(seq(nrow(df_correction)), .init = vct_string, ~ gsub(df_correction$pattern[.y], df_correction$replacement[.y], .x))
#> [1] "old car" "new car" "house" "old house"
這甚至會在給定向量的元素中進行多次替換。 看到這個
#modified example
vct_string <- c("old ccar","new carr", "house", "oold carr")
purrr::reduce(seq(nrow(df_correction)), .init = vct_string, ~ gsub(df_correction$pattern[.y], df_correction$replacement[.y], .x))
[1] "old car" "new car" "house" "old car"
首先寫一個 function 用於替換
word_correct <- function(string) {
df_correction <- data.frame(
pattern = c("old ccar", " new carr", "oold house", "house"), # changed from OP
replacement = c("car", "car", "old", "house"),
stringsAsFactors = FALSE
)
df_correction[ which(df_correction$pattern == string), "replacement"]
}
# Testing
word_correct("oold")
word_correct("ccar")
然后你可以將 function 作為參數傳遞給purrr::map
map_chr(vct_string, word_correct) # using map_chr to return a vector instead of a list which is what map returns
由於您使用映射表來替換單個單詞,因此您實際上可以在第二個 function 中使用map
來獲得您想要的結果。
vct_string <- c("old ccar","new carr", "house", "oold house")
single_word_correct <- function(string) {
df_correction <- data.frame(
pattern = c("ccar", "carr", "oold"),
replacement = c("car", "car", "old"),
stringsAsFactors = FALSE
)
if(string %in% df_correction$pattern){
df_correction[ which(df_correction$pattern == string), "replacement"]
} else {
string
}
}
multi_word_correct <- function(string){
strings <- strsplit(string, " ")[[1]]
paste(map_chr(strings, single_word_correct), collapse = " ")
}
map_chr(vct_string, multi_word_correct)
下面是使用 base::Reduce 的方法:
Reduce(function(x, y) {
gsub(df_correction[y, 1], df_correction[y, 2], x)
}, init = vct_string, 1:nrow(df_correction))
[1] "old car" "new car" "house" "old house"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.