Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
1 view
by (50.2k points)

I have created a dataframe like below:

dfm = data.frame (names = c('email', 'Facebook', 'walmart', 'target', 'instagram', 'costco'))

And in that I want to create a new column source. When names are facebook, instagram or email, source is media. When names are costco,walmart or target, the source is store.

I use the following case_when() and str_detect(). I need to the str_detect to be case insensitive. So below is my code.

dfm %>% 

  mutate(source = case_when( str_detect(names, fixed('email|facebook|instagram', ignore_case = T))~'media',

                             str_detect(names, 'walmart|costco|target')~ 'store'))

I got:

names       source

email       NA          

Facebook    NA          

walmart     store           

target      store           

instagram   NA          

costco      store

I do not understand why it did not work. Does anyone know why?

I tried the code below, it returns TRUE:

str_detect('Facebook', fixed('facebook', ignore_case = T))

1 Answer

0 votes
by (108k points)

See when you have used fixed the this will not get | as regex. If you want to do exact match use word boundaries i.e \\b, refer the following code:

library(dplyr)

library(stringr)

dfm %>% 

   mutate(source = case_when(str_detect(names, 

                 regex('\\bemail\\b|\\bfacebook\\b|\\binstagram\\b', 

                        ignore_case = TRUE))~'media',

                  str_detect(names, 'walmart|costco|target')~ 'store'))

#      names source

#1     email  media

#2  Facebook  media

#3   walmart  store

#4    target  store

#5 instagram  media

#6    costco  store

If you want to know more about R then do check out the following R programming tutorial that will help you in learning R from basics. 

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...