繁体   English   中英

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

[英]Replace same text with multiple strings in R

这是我的示例数据:

root <- c("how to manage xxx","how to run xxx","how to operate xxx")
type <- c("resturant","grocery store","retail store")

我想用“类型”中的每个字符串替换xxx。 现在,我按如下方式使用gsub函数,但它一次只能替换一个查询。

kw <- gsub("xxx", "123", root)

结果应为:

how to manage restaurant
how to run restaurant
how to operate resturant
how to manage grocery store
...
how to operate retail store

regmatches<-魔术:

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

如果需要创建新值,则需要首先重复原始的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" 
data.frame(x = unlist(lapply(type, function(x) gsub("xxx",x,root))))
#                             x
#1      how to manage resturant
#2         how to run resturant
#3     how to operate resturant
#4  how to manage grocery store
#5     how to run grocery store
#6 how to operate grocery store
#7   how to manage retail store
#8      how to run retail store
#9  how to operate retail store

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM