Home > Mobile >  How to apply an anonymous function inside dplyr mutate_at pipeline in a rowwise manor?
How to apply an anonymous function inside dplyr mutate_at pipeline in a rowwise manor?

Time:06-26

A trivial reproducible example is presented below, I want to mutate the mtcars dataframe at variables vs and vm such that if the value is equal to 1 it is changed to 2. Below is my original approach, which produces error the condition has length > 1. So obviously it's not iterating through each element in the vector.

mtcars %>% mutate_at(vars(vs,am),function(x) {if(x == 1){x <- 2}})

My second approach was to try a lapply to iterate over each element in the vector, which also gave me an error Error in match.fun(FUN) : argument "FUN" is missing, with no default.

mtcars %>% mutate_at(vars(vs,am),lapply(function(x) {if(x == 1){x <- 2}}))

I obviously know how to accomplish this in a for loop, just want to understand the logic behind the scenes.

CodePudding user response:

mtcars %>%
    mutate(across(c(vs, am), ~ case_when(.x == 1 ~ 2, TRUE ~ .x)))
  • Related