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(.)
)))
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.
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(.)
)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With