Search code examples
rcase-when

How to keep original values of cells if they do not meet criterion in case when at R?


I want the mutate to run on all cells values (edited: in DF with multiple columns), and if it doesn't meet any criterion of the case_when, to keep the original data. for example mutate(~case_when(.=="hi" ~1, .=="hello"~2, T~(keep original value) ))


Solution

  • If you are running case_when only for 1 column you can refer to the column name itself in TRUE ~

    library(dplyr)
    
    df %>%
      mutate(cyl = case_when(col == 'hi' ~ 1, 
                             col == 'hello' ~ 2, 
                             TRUE ~ col))
    

    If you are running this for multiple columns with mutate_at/across you can use .

    df %>%
      mutate(across(c(a, b), ~case_when(.== "hi" ~ 1, 
                                        .== "hello"~2, 
                                        TRUE ~ .)))