Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the following vector of hashtags:

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

And I'm trying to write a code that says if a string is NOT present (in this example, let's say "#datascienceinR"), then append it to the vector. If it is there, no other action needs to be taken. I've tried this:

library(tidyverse)

all_hashtags <- if(str_detect(hashtags, "#datascienceinR") = FALSE) {

  append(hashtags, "#datascienceinR")

}

But I get this error:

Error: unexpected '=' in "all_hashtags <- if(str_detect(hashtags, "#datascienceinR") ="

>   append(hashtags, "#datascienceinR")

[1] "#data"             

[2] "#datascience"      

[3] "#datascienceiscool"

[4] "#datascienceinR"   

> }

Error: unexpected '}' in "}"

Any suggestions?

1 Answer

0 votes
by (36.8k points)
edited by

The = is assignment operator and not == (comparison operator)

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

                                           ^

Also, instead of doing the == FALSE, it is better to negate (!)

!str_detect(hashtags, "#datascienceinR")

The third issue is the use of if/else as if/else expects a logical vector of length 1 and not more than one. Here, the 'hashtags' is a vector of length 3 and the str_detect also returns the same length of TRUE/FALSE logical vector. So, we need to wrap with all

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

       append(hashtags, "#datascienceinR")

 } 

all_hashtags

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

It can also be written with the union (assuming there are no duplicate elements)

hashtags <- union(hashtags, "datascienceinR")  

If there are duplicate elements and want to keep them, another option is union from vessels

library(vecsets)

hashtags <- vunion(hashtags, "datascienceinR")  

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...