如何在if语句r中使用str_detect为FALSE的方式来追加一个值。

问题描述 投票:0回答:1

我有下面的标签向量,我想写一个代码,如果一个字符串不存在(比如 "#datascienceinR"),就把它追加到向量中。

hashtags <- c("#data", "#datascience", "#datascienceiscool")

我想写一段代码,如果一个字符串不存在(在这个例子中,比如 "#datascienceinR"),就把它追加到向量中。如果它是存在的,就不需要采取其他操作。我已经试过了。

library(tidyverse)
all_hashtags <- if(str_detect(hashtags, "#datascienceinR") = FALSE) {
  append(hashtags, "#datascienceinR")
}

但我得到了这个错误。


Error: unexpected '=' in "all_hashtags <- if(str_detect(hashtags, "#datascienceinR") ="
>   append(hashtags, "#datascienceinR")
[1] "#data"             
[2] "#datascience"      
[3] "#datascienceiscool"
[4] "#datascienceinR"   
> }
Error: unexpected '}' in "}"

有什么建议吗?

r string if-statement append stringr
1个回答
1
投票

= 是赋值运算符,而不是 == (比较运算符)

if(str_detect(hashtags, "#datascienceinR") = FALSE)
                                           ^

此外,不做 == FALSE,最好是否定(!)

!str_detect(hashtags, "#datascienceinR")

第三个问题是使用 if/else 作为 if/else 希望是一个长度为1的逻辑向量,且不超过一个。 这里,'hashtags'是一个长度为3的向量,而 str_detect 也返回同样长度的TRUEFALSE逻辑向量。 所以,我们需要用 all

all_hashtags <- if(all(!str_detect(hashtags, "#datascienceinR"))) {
       append(hashtags, "#datascienceinR")
 } 

all_hashtags
#[1] "#data"              "#datascience"       "#datascienceiscool" "#datascienceinR"

也可以写成 union (假设没有重复的元素)

hashtags <- union(hashtags, "datascienceinR")  

如果有重复的元素而又想保留它们,另一个选择是 vunionvecsets

library(vecsets)
hashtags <- vunion(hashtags, "datascienceinR")  
© www.soinside.com 2019 - 2024. All rights reserved.