How to mutate a column in tidyverse for 'if text contains text string'

Viewed 2246

How do I edit this code to replace == with if the Species contains %setosa%

new_iris <- iris %>% 
   mutate(flag = ifelse(Species == "setosa", 1, 0)  # add a new column
          )
2 Answers

To stay in the tidyverse you could use stringr.

library(dplyr)
library(stringr)

 iris %>%
    mutate(flag = str_detect(Species, "setosa"))

We can use %like% from data.table

library(dplyr)
library(data.table)
iris %>% 
     mutate( flag = as.integer(Species %like% "setosa") )
Related