Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr Replace values in multiple variables

I need to replace non-4 with 80 in cyl, gear, carb columns. I tried the following, but it does not work.

mtcars %>% mutate_at(vars(cyl, gear, carb), replace(which(.!=4), 80))

It throws the following error:

Error in replace(which(. != 4), 80) : 
  argument "values" is missing, with no default

What am I missing here?

like image 297
Geet Avatar asked Oct 24 '25 14:10

Geet


1 Answers

You need to pass a function or formula to mutate_at as second argument:

mtcars %>% mutate_at(vars(cyl, gear, carb), ~ replace(., which(.!=4), 80))

Or create the function using funs:

mtcars %>% mutate_at(vars(cyl, gear, carb), funs(replace(., which(.!=4), 80)))
like image 82
Psidom Avatar answered Oct 27 '25 03:10

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!