Search code examples
rtidyversedplyracross

Mutate specific columns based on position


I trying to convert all negative values to 0 in specific columns of a dataframe. How would I for an example convert negative values to zero in column 3:5 and 8 in the mtcars data?

mtcars <- mtcars%>%
mutate(across(c(3:5,8), funs(replace(., .<0, 0)))

Thanks a lot for any help!


Solution

  • This could be achieved like so:

    library(dplyr)
    
    mtcars <- mtcars %>%
      mutate(across(c(3:5,8), ~ if_else(. < 0, 0, .)))