简体   繁体   中英

Using dplyr::mutate_at with case_when conditional on another variable

I want to transform a set of variables differently depending on a condition. I found a solution here

Example: I want to substract 4 from all variables 'mpg' to 'disp' if 'gear' equals 4, otherwise I substract 3.

mtcars %>% 
  mutate_at(vars(mpg:disp),
            funs(case_when(gear == 4 ~ . - 4L, TRUE ~ . -3L))) 

But I get this warning:

funs() is soft deprecated as of dplyr 0.8.0
Please use a list of either functions or lambdas: 

# Simple named list: 
`list(mean = mean, median = median)`
# Auto named with `tibble::lst()`: 
`tibble::lst(mean, median)`
# Using lambdas
`list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))`

This warning is displayed once per session.  

Is there a better solution to my problem that avoids using funs() ?

重现这样做

mtcars %>% mutate_at(vars(mpg:disp), ~ case_when(gear == 4 ~ . - 4L, TRUE ~ . -3L)) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM