Using case_when within mutate_at

2020-02-28 10:27发布

问题:

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.

回答1:

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(.)
        ))) 


标签: r dplyr mutate