我试图根据ifelse语句在字符串末尾添加一个单词并遇到麻烦。
words <- c("one","two","one","four")
newword <- "word"
然后如果值等于&#34;一个&#34;,我想附加一个单词
words <- ifelse(words == "one",
gsub(paste(newword, sep = " "), "", words),
words)
我希望输出为
words
[1] "one word" "two" "one word" "four"
任何想法为什么我不能用ifelse和paste()函数来实现这个目标?
感谢您的帮助!
答案 0 :(得分:2)
让我在OP要求之后写下我的想法。一种方法是使用gsub()
。你寻找模式,&#34;一个&#34;并通过粘贴&#34;一个&#34;(代表\\1
)和新词来替换它。另一种方法是使用which()
。您查找元素的索引号,&#34;一个&#34;。对于那些索引号位置,您要添加paste("one", newword, sep = " ")
。
gsub(x = words, pattern = "(one)", replacement = paste("\\1", newword, sep = " "))
words[which(words == "one")] <- paste("one", newword, sep = " ")
答案 1 :(得分:1)
您不需要gsub
和paste
。
以下是如何使用ifelse
和paste
(这可能就是我要这样做):
ifelse(words == "one", paste(words, newword), words)
# [1] "one word" "two" "one word" "four"
以下是paste
如何做到这一点。 (创建一个新变量,以便原始对象对于下一个方法保持不变。)
words2 = words
words2[words2 == "one"] = paste(words2[words2 == "one"], newword)
words2
# [1] "one word" "two" "one word" "four"
以下是gsub
:
gsub(pattern = "(one)", x = words, replacement = paste("\\1", newword))
# [1] "one word" "two" "one word" "four"