简体   繁体   中英

Using “across” to change multiple columns in dplyr

I have 100 columns that are all numeric. The first column is an ID number, which needs to stay numeric, and I need to change the other columns to factors. I have been trying to use the new(ish) across function from dplyr to do this, but I cannot successfully apply the function to all columns except the first one. From what I've read, I should be able to do the following:

df %>% mutate(across(everything(!c(ID)), as.factor))

But this gives the error: "Can't subset columns that don't exist. Locations 101, 102, etc. do not exist." What am I doing wrong?

Instead of the negate ( ! ) in everything , we just need - or as @27 ϕ 9 mentioned ! also works without the everything

library(dplyr)
df <- df %>%
     mutate(across(-ID, factor))

If there are more than one column, wrap it inside c

df <- df %>%
        mutate(across(-c(ID, ID2), factor))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM