Codezy
Codezy

Reputation: 662

How can I replace the same character with different strings at different positions?

v1 <- c("X is the girlfriend of X.","X is the teacher of X.")
v2 <- c("Lily","John")
gsub("X",v2[1],v1)
gsub("X",v2[2],v1)


> gsub("X",v2[1],v1)  #what i can do now
[1] "Lily is the girlfriend of Lily." "Lily is the teacher of Lily."  
> str_replace(v1, "X", v2)  #the answer from Relasta, thank you
[1] "Lily is the girlfriend of X." "John is the teacher of X." 

Ideal Result
"Lily is the girlfriend of John." "Lily is the teacher of John." 

Hello, I want to replace the same character in a vector with 2 different characters on a large scale. And I have made an example up there. Now I can only replace the character X by one kind of character. My ideal result is like "Lily is the girlfriend of John." "Lily is the teacher of John.". How can I do that?

Upvotes: 0

Views: 52

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47350

sprintf works very well for your purpose:

sprintf(c("%s is the girlfriend of %s.","%s is the teacher of %s."),"Lily","John")
# [1] "Lily is the girlfriend of John." "Lily is the teacher of John."

starting from your data:

v1b <- gsub("X","%s",v1,fixed=T)
do.call(sprintf,c(list(v1b),v2))
# [1] "Lily is the girlfriend of John." "Lily is the teacher of John." 

Upvotes: 1

talat
talat

Reputation: 70336

You can use an lapply-loop with sub:

invisible(lapply(v2, function(z) v1 <<- sub("X", z, v1, fixed=TRUE)))
v1
#[1] "Lily is the girlfriend of John." "Lily is the teacher of John."   

This works in the way that in each loop iteration (along v2) the first X in each vector is replaced with the current value of v2. Since we use <<- to update v1 in the global environment, the loop doesn't replace the same X in the second iteration as it did in the first (previous) one.

Upvotes: 2

Relasta
Relasta

Reputation: 1106

You could try the stringr package and str_replace. It is vectorised so you do not need to repeat the lines of code.

v1 <- c("My name is X.","X is my name")
v2 <- c("Lily","John")

library(stringr)
str_replace(v1, "X", v2)

# [1] "My name is Lily." "John is my name" 

Upvotes: 2

Related Questions