简体   繁体   中英

mutate_if() multiple conditions

mpg |>
  dplyr::mutate_if(is.character, as.factor) |>
  dplyr::mutate_if(is.logical, as.factor) |>
  dplyr::mutate_if(is.integer, as.numeric)

I have the above code. Is there a more simple way to write this code without calling mutate_if three times?

If you check the documentation of mutate_if , it's been superseded by across() .

So the above code could be written as:

library(dplyr)

mpg %>% 
  mutate(across(where(is.character) | where(is.logical), as.factor),
         across(where(is.integer), as.numeric))

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