Search code examples
rdplyrmultiple-columns

Change multiple columns to lowercase with dplyr. Difficulty with mutate across everything minus


I want to change multiple columns (in real data approx 20 columns) to lower case. I think it would be easier to select these by excluding those I don't want to change.

Example data:

risk = data.frame(title = c("foo", "bar", "blah"),
                  a= c("y", "Y", "n"),
                  b= c("N", "y", "Y"),
                  Summary = rep(NA, 3))

I want to mutate columns 2 and 3 (aand b)

I've done it with base R but I'd be interested in understanding the dplyr error and in my real data there are many more columns and dplyr would be quicker

successful base R attempt

risk[,c(2,3)] = lapply(risk[,c(2,3)], tolower)

dplyr attempt (to change everything minus some columns)

 risk = risk%>%
   mutate(across(everything()- risk[,c(1,4)]), ~tolower(.))

with resulting error:

Error: Problem with `mutate()` input `..1`.
i `..1 = across(everything() - risk[, c(1, 4)])`.
x non-numeric argument to binary operator

I've done it with base R but I'd be interested in understanding the dplyr error


Solution

  • If you want to apply it to all columns then this is enough:

    risk %>% mutate(across(2:3, tolower))