Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr mutate_at and case_when

Tags:

r

dplyr

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!

like image 666
lost Avatar asked Apr 01 '18 04:04

lost


1 Answers

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 ~ .
    ))
  )
like image 121
Psidom Avatar answered Nov 16 '22 15:11

Psidom