根据条件语句向字符串添加单词

时间:2018-01-20 03:29:33

标签: r string if-statement character

我试图根据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()函数来实现这个目标?

感谢您的帮助!

2 个答案:

答案 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)

您不需要gsubpaste

以下是如何使用ifelsepaste(这可能就是我要这样做):

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"