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.
>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...