Reputation: 1765
I have a dataframe with a few character columns and many numerical columns. I need to replace all the numerical values in all the columns greater than 1 with 1, without modifying the character columns. I use mutate_if to achieve my goal but the problem I face is that it's automatically rounding the data and I don't want that. How can I avoid the rounding? This is my sample code:
mtcars$TEXT <- rownames(mtcars)
mtcars %>% mutate_if(is.numeric, ~4.00 * (. > 4))
if you print it, you will notice all the values are now either 4 or 0. I'm really confused and can't figure out why. Thanks
Upvotes: 1
Views: 308
Reputation: 78927
Edit: Thanks to Gregor Thomas and the feedback of the community: Here is the edited version:
library(dplyr)
# old solution
# mtcars %>% mutate(across(where(is.numeric), ~case_when(is.numeric(.) & . > 1 ~ 1, TRUE ~ .)))
# new solution implementing the advice of Gregor Thomas and Hong Ooi
mtcars %>% mutate(across(where(is.numeric), pmin, 1))
data:
mtcars$TEXT <- rownames(mtcars)
mtcars %>% mutate_if(is.numeric, ~4.00 * (. > 4))
Output:
mpg cyl disp hp drat wt qsec vs am gear carb TEXT
Mazda RX4 1 1 1 1 1 1 1 0 1 1 1 Mazda RX4
Mazda RX4 Wag 1 1 1 1 1 1 1 0 1 1 1 Mazda RX4 Wag
Datsun 710 1 1 1 1 1 1 1 1 1 1 1 Datsun 710
Hornet 4 Drive 1 1 1 1 1 1 1 1 0 1 1 Hornet 4 Drive
Hornet Sportabout 1 1 1 1 1 1 1 0 0 1 1 Hornet Sportabout
Valiant 1 1 1 1 1 1 1 1 0 1 1 Valiant
Duster 360 1 1 1 1 1 1 1 0 0 1 1 Duster 360
Merc 240D 1 1 1 1 1 1 1 1 0 1 1 Merc 240D
Merc 230 1 1 1 1 1 1 1 1 0 1 1 Merc 230
Merc 280 1 1 1 1 1 1 1 1 0 1 1 Merc 280
Merc 280C 1 1 1 1 1 1 1 1 0 1 1 Merc 280C
Merc 450SE 1 1 1 1 1 1 1 0 0 1 1 Merc 450SE
Merc 450SL 1 1 1 1 1 1 1 0 0 1 1 Merc 450SL
Merc 450SLC 1 1 1 1 1 1 1 0 0 1 1 Merc 450SLC
Cadillac Fleetwood 1 1 1 1 1 1 1 0 0 1 1 Cadillac Fleetwood
Lincoln Continental 1 1 1 1 1 1 1 0 0 1 1 Lincoln Continental
Chrysler Imperial 1 1 1 1 1 1 1 0 0 1 1 Chrysler Imperial
Fiat 128 1 1 1 1 1 1 1 1 1 1 1 Fiat 128
Honda Civic 1 1 1 1 1 1 1 1 1 1 1 Honda Civic
Toyota Corolla 1 1 1 1 1 1 1 1 1 1 1 Toyota Corolla
Toyota Corona 1 1 1 1 1 1 1 1 0 1 1 Toyota Corona
Dodge Challenger 1 1 1 1 1 1 1 0 0 1 1 Dodge Challenger
AMC Javelin 1 1 1 1 1 1 1 0 0 1 1 AMC Javelin
Camaro Z28 1 1 1 1 1 1 1 0 0 1 1 Camaro Z28
Pontiac Firebird 1 1 1 1 1 1 1 0 0 1 1 Pontiac Firebird
Fiat X1-9 1 1 1 1 1 1 1 1 1 1 1 Fiat X1-9
Porsche 914-2 1 1 1 1 1 1 1 0 1 1 1 Porsche 914-2
Lotus Europa 1 1 1 1 1 1 1 1 1 1 1 Lotus Europa
Ford Pantera L 1 1 1 1 1 1 1 0 1 1 1 Ford Pantera L
Ferrari Dino 1 1 1 1 1 1 1 0 1 1 1 Ferrari Dino
Maserati Bora 1 1 1 1 1 1 1 0 1 1 1 Maserati Bora
Volvo 142E 1 1 1 1 1 1 1 1 1 1 1 Volvo 142E
Upvotes: 1