根据条件语句向字符串添加单词(Add a word to a string based on a conditional statement)

编程入门 行业动态 更新时间:2024-10-23 05:36:09
根据条件语句向字符串添加单词(Add a word to a string based on a conditional statement)

我试图根据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 = " ")

更多推荐

本文发布于:2023-08-01 03:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1352833.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   语句   单词   条件   Add

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!