how do I set multiple existing columns in a dataframe to factors?

basically suppose I have 10 columns: (a-j) and columns b and g are the columns that are currently numeric and want to set to factors. How to set these specific columns as factors rather than doing as.factor() and adding them to my existing data frame (my data frame for this example is dataInExample?

libraries I am using are dplyr, and tidyverse

would I use select()?

dataInExample <- as.factor(dataInExample$b) #rather than this and then add it again
dataInExample <- some R code that converts columns b and g to factors in dataInExample

You can do something like this

library(dplyr)

dataInExample  %>% 
    mutate(across(.cols = c(b, g),
                  .fns = as.factor))

If you need more specific help, please provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like

Thank you so much, it worked!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.