Search code examples
rdplyrcase-when

Trouble making a new column using case_when in Dplyr


I'm try to make a new column in my data frame which will contain only the receivers we set up in one are of study. I've checked other pages on here but I still get the same error:

<error/dplyr:::mutate_error> Problem with mutate() input ER. x Case 1 (Receiver %in% c("1326", "1315", "1314", "1321", "1404", "1318", "1325", "1313...) must be a two-sided formula, not a logical vector. i Input ER is case_when(...). Backtrace: Run rlang::last_trace() to see the full context.

I've tried:

ev<-ev %>% 
  select(Receiver) %>% 
  mutate(ER=case_when(c(Receiver=="1315"|
                         Receiver=="1314"|
                         Receiver=="1321"|
                        Receiver=="1404"|
                        Receiver=="1318"|
                        Receiver=="1325"|
                        Receiver=="1313"|
                        Receiver=="1323"|
                        Receiver=="1324"|
                        Receiver=="1320"|
                        Receiver=="1319"|
                        Receiver=="1317")))

And:

ev<-ev %>%   
  mutate(ER=case_when(Receiver %in% c("1326", "1315", "1314", "1321", "1404", "1318", "1325", "1313", "1323", "1324", "1320", "1319", "1317")))

Any help showing me where I've gone wrong is much appreciated.


Solution

  • Let's assume you have two studies, study_A and study_B. Then you need to add replacement values e.g. for only two of your given strings:

    ev <- ev %>%
       mutate(ER = case_when(Receiver == "1326" ~ "study_A", 
                             Receiver == "1315" ~ "study_B"))