用R中的多个字符串替换相同的文本

Ran*_*Tao 1 text r data-manipulation

这是我的示例数据:

root <- c("how to manage xxx","how to run xxx","how to operate xxx")
type <- c("resturant","grocery store","retail store")
Run Code Online (Sandbox Code Playgroud)

我想用"type"中的每个字符串替换xxx.现在我使用gsub函数如下,但它一次只能替换一个查询.

kw <- gsub("xxx", "123", root)
Run Code Online (Sandbox Code Playgroud)

结果应该是:

how to manage restaurant
how to run restaurant
how to operate resturant
how to manage grocery store
...
how to operate retail store
Run Code Online (Sandbox Code Playgroud)

the*_*ail 5

regmatches<- 魔法:

regmatches(root, regexpr("xxx",root)) <- type
root
#[1] "how to manage resturant"     "how to run grocery store"   
#[3] "how to operate retail store"
Run Code Online (Sandbox Code Playgroud)

如果您需要创建新值,则需要先重复原始root矢量:

out <- rep(root,each=length(type))
regmatches(out, regexpr("xxx",out)) <- type
out
#[1] "how to manage resturant"      "how to manage grocery store" 
#[3] "how to manage retail store"   "how to run resturant"        
#[5] "how to run grocery store"     "how to run retail store"     
#[7] "how to operate resturant"     "how to operate grocery store"
#[9] "how to operate retail store" 
Run Code Online (Sandbox Code Playgroud)