Search code examples
rdplyrstringrmagrittr

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?


Solution

  • 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)))