Case_when mutate str_detect

Hello community

I am trying to print A if the col2 contain the letter a.
It is not working properly and I would like to know if Should I write ?a or !a

df %>%
  mutate(col1 = case_when(
    str_detect(col2, pattern = "a") ~ "A"))

From my perspective it seems to be working:

library(tidyverse)

df = tibble(col2 = c("apple", "orange", "kiwi"))

df %>%
  mutate(col1 = case_when(
    str_detect(col2, pattern = "a") ~ "A"))
#> # A tibble: 3 x 2
#>   col2   col1 
#>   <chr>  <chr>
#> 1 apple  A    
#> 2 orange A    
#> 3 kiwi   <NA>

Created on 2021-12-22 by the reprex package (v2.0.1)

Often when asking for help with coding, it is useful to provide a "reproducible example" of your own code (use dput(head(your_data, 100))) and explain what exactly isn't working (is there an error message? Is it not doing what you'd expect it to?)

1 Like

mutate(col1 = if_else(grepl(“a”, col2) , “A”, col1))

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.