Ran Tao
Ran Tao

Reputation: 311

Replace same text with multiple strings in R

Here is my sample data:

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

I would like to replace xxx with each string in "type". Now I am using gsub function as follow, but it can only replace one query at one time.

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

The result should be like:

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

Upvotes: 1

Views: 127

Answers (2)

thelatemail
thelatemail

Reputation: 93938

regmatches<- magic:

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

If you need to create new values, you'll need to repeat your original root vector first:

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" 

Upvotes: 5

d.b
d.b

Reputation: 32558

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

Upvotes: 2

Related Questions