I'd like to identify variables with starts_with() and then perform a case_when mutation.
For example, let's say I want to do the equivalent of:
mtcars$mpg[mtcars$mpg == 21.0] <- 5; mtcars
My attempt:
mtcars %>%
mutate_at(
vars(starts_with("mpg")),
funs(. = case_when(
. == 21.0 ~ 5,
TRUE ~ .
))
)
What am I doing wrong? The dplyr documentation doesn't seem to have many examples of mutate_at/mutate_each (this thread seems to have the same complaint), so I have a hard time with these functions. Maybe I am not looking in the right place?
I'm aware of this thread but wasn't able to find a solution in there.
Thanks!
funs
creates a list of functions, when you do funs(. = ...)
, it creates named functions with name of .
, and this leads to new column(s) being generated with either the name of .
if you have only one column, or the name with suffix of .
if you have more than one column to mutate; If you need to overwrite the original column, simply leave the functions unnamed by directly passing the anonymous function to funs
. In your case, removing . =
in funs
should work;
mtcars %>%
mutate_at(
vars(starts_with("mpg")),
funs(case_when(
. == 21.0 ~ 5,
TRUE ~ .
))
)
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