我试图在R中应用gsub来将字符串a中的匹配替换为字符串b中的相应匹配.例如:
a <- c("don't", "i'm", "he'd")
b <- c("do not", "i am", "he would")
c <- c("i'm going to the party", "he'd go too")
newc <- gsub(a, b, c)
Run Code Online (Sandbox Code Playgroud)
这样newc ="我要参加聚会","他也会参加聚会".这种方法不起作用,因为gsub只接受a和b的长度为1的字符串.执行循环以循环a和b将非常慢,因为实数a和b的长度为90且c的长度> 200,000.R中是否有矢量化方式来执行此操作?
G. *_*eck 14
1)gsubfn gsubfn
包中的gsubfn就像gsub
替换字符串一样,可以是字符串,列表,函数或proto对象.如果它是一个列表,它将用名称等于匹配字符串的列表组件替换每个匹配的字符串.
library(gsubfn)
gsubfn("\\S+", setNames(as.list(b), a), c)
Run Code Online (Sandbox Code Playgroud)
赠送:
[1] "i am going to the party" "he would go too"
Run Code Online (Sandbox Code Playgroud)
2)gsub对于没有包的解决方案,请尝试以下循环:
cc <- c
for(i in seq_along(a)) cc <- gsub(a[i], b[i], cc, fixed = TRUE)
Run Code Online (Sandbox Code Playgroud)
赠送:
> cc
[1] "i am going to the party" "he would go too"
Run Code Online (Sandbox Code Playgroud)
stringr::str_replace_all()
是一个选项:
library(stringr)
names(b) <- a
str_replace_all(c, b)
[1] "i am going to the party" "he would go too"
Run Code Online (Sandbox Code Playgroud)
这是相同的代码,但带有不同的标签,希望能让它更清晰一点:
to_replace <- a
replace_with <- b
target_text <- c
names(replace_with) <- to_replace
str_replace_all(target_text, replace_with)
Run Code Online (Sandbox Code Playgroud)