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."
您好,我想在大规模的2个不同字符的向量中替换相同的字符。我在那里做了一个例子。现在我只能用一种角色替换角色X.我的理想结果就像“莉莉是约翰的女朋友”。 “莉莉是约翰的老师。”我怎么能这样做?
答案 0 :(得分:2)
您可以尝试stringr
包和str_replace
。它是矢量化的,因此您无需重复代码行。
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"
答案 1 :(得分:2)
您可以使用带sub
的lapply循环:
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."
这适用于在每次循环迭代(沿v2)中每个向量中的 first X被当前值v2替换的方式。由于我们在全局环境中使用<<-
更新v1
,因此循环不会在第二次迭代中替换与第一次(上一次)迭代中相同的X.
答案 2 :(得分:1)
B<A>
非常适合您的目的:
sprintf
从您的数据开始:
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."