biostatguy12
biostatguy12

Reputation: 659

ignore_case in ifelse statment r?

is there a way to do an ifelse by ignoring case? for example if I have a name variable and 'example' can be 'Example' or 'EXAMPLE' I would like to pick this up as flag==1.

df%>%mutate(flag=ifelse((name=='example', 1, 0))

Upvotes: 1

Views: 90

Answers (2)

akrun
akrun

Reputation: 887008

With str_detect, we can use modifiers

library(dplyr)
library(stringr)
df %>% 
    mutate(flag = as.integer(str_detect(name, 
               regex("example|othername", ignore_case = TRUE))))
#      name flag
#1   example    1
#2   Example    1
#3   EXAmple    1
#4     hello    0
#5       ggg    0
#6 othername    1

data

df <- data.frame(name = c('example', 'Example', 'EXAmple',
     'hello', 'ggg', 'othername'), stringsAsFactors = FALSE)

Upvotes: 1

arg0naut91
arg0naut91

Reputation: 14764

Try:

df %>% 
  mutate(flag = +(tolower(name) %in% c('example', 'othername')))

You could also do:

df %>% 
  mutate(flag = +(grepl('^(example|othername)$', name, ignore.case = TRUE)))

Upvotes: 2

Related Questions