我试图根据ifelse语句在字符串末尾添加一个单词并遇到麻烦。
words <- c("one","two","one","four") newword <- "word"如果值等于“1”,我想附加一个单词
words <- ifelse(words == "one", gsub(paste(newword, sep = " "), "", words), words)我想要输出
words [1] "one word" "two" "one word" "four"任何想法为什么我不能用ifelse和paste()函数实现这一点?
谢谢您的帮助!
I'm trying to add a word to the end of a string based on an ifelse statement and having trouble.
words <- c("one","two","one","four") newword <- "word"and then if the value equals "one", I want to append a word
words <- ifelse(words == "one", gsub(paste(newword, sep = " "), "", words), words)I want the output to be
words [1] "one word" "two" "one word" "four"any idea why I can't make this happen with an ifelse and the paste() function?
Thanks for the help!
最满意答案
自OP要求以来,让我写下我的想法。 一种方法是使用gsub() 。 您查找模式“one”并通过粘贴“one”(表示为\\1 )和newword来替换它。 另一种方法是使用which() 。 您查找元素的索引号“one”。 对于那些索引号位置,您需要添加paste("one", newword, sep = " ") 。
gsub(x = words, pattern = "(one)", replacement = paste("\\1", newword, sep = " ")) words[which(words == "one")] <- paste("one", newword, sep = " ")Let me write up my ideas since the OP requested it. One way is to use gsub(). You look for the pattern, "one" and replace it by pasting "one", which is represented as \\1, and newword. The other way is to use which(). You look for index numbers for the element, "one". For those index number positions, you want to add paste("one", newword, sep = " ").
gsub(x = words, pattern = "(one)", replacement = paste("\\1", newword, sep = " ")) words[which(words == "one")] <- paste("one", newword, sep = " ")更多推荐
发布评论