Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using case_when within mutate_at

Tags:

r

dplyr

I would like to use case_when within mutate_at, as in the following example:

mtcars %>% 
  mutate_at(.vars = vars(vs, am),
            .funs = funs(case_when(
              . %in% c(1,0,9) ~ TRUE
              . %in% c(2,20,200) ~ FALSE
              TRUE ~ as.character(.)
            )))

alternative version using . = in funs() call also does not work.

mtcars %>%
  mutate_at(.vars = vars(vs, am),
            .funs = funs(. = case_when(
              . %in% c(1, 0, 9) ~ TRUE
              . %in% c(2, 20, 200) ~ FALSE
              TRUE ~ as.character(.)
            )))

Desired results

mtcars %>% 
  mutate_at(.vars = vars(vs, am),
         .funs = funs(ifelse(. %in% c(1, 0, 9), TRUE, FALSE)))

FALSE could be replaced with second ifelse() call, which I didn't include for brevity.

like image 551
Konrad Avatar asked Dec 19 '17 13:12

Konrad


1 Answers

We need , to separate each case. Also, if we are keeping the last option as character, then the TRUE/FALSE should be character as well. No mixing of types

mtcars %>%
  mutate_at(.vars = vars(vs, am),
        .funs = funs(. = case_when(
          . %in% c(1, 0, 9) ~ TRUE,
          . %in% c(2, 20, 200) ~ FALSE,
          TRUE ~ TRUE
        )))

If we need to make character class and also to return the column as character if either of the two cases are not correct, perhaps

mtcars %>%
 mutate_at(.vars = vars(vs, am),
        .funs = funs(. = case_when(
          . %in% c(1, 0, 9) ~ "Yes",
          . %in% c(2, 20, 200) ~ "No",
          TRUE ~ as.character(.)
        ))) 
like image 63
akrun Avatar answered Oct 06 '22 23:10

akrun