Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dplyr mutate_if numeric columns but exclude a column or condition on numeric value

I have a very simple need on a data frame with large number of numeric columns. I want to round down all numeric values to one decimal max, but exclude one specific column by name or position or whatever from this rounding.

For example, in this case, I don’t want drat column to be rounded down, let us say.

mtcars %>% mutate_if(is.numeric, round, 1)

How can I do this, without having enumerate all columns? BTW – my data has non-numeric columns too, and so mutate_if sounds right.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use mutate/across as shown. drat can be replaced with 5 if desired since drat is the fifth column. If we had ix <- "drat" or ix <- 5 then replace drat with all_of(ix) .

library(dplyr)
mtcars %>% mutate(across(where(is.numeric) & !drat, ~ round(.x, 1)))

giving

                     mpg cyl  disp  hp drat  wt qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.6 16.5  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.9 17.0  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.3 18.6  1  1    4    1
...snip...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading