简体   繁体   中英

Converting columns of a dataframe to factor

I have a data frame with 100 columns and I want to convert them all into factor. Let's assume the data frame,

a <- as.integer(c(1,2,1,2,1,1))
b <- as.integer(c(1,2,3,3,3,1))
df <- data.frame(a,b)

I am trying this,

library(dplyr)
colwise(df, as.factor(df))

which give me an error like this,

> colwise(df, as.factor(df))
Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

Any suggestion how to do this correct? Thanks in advance.

With dplyr , we use factor within mutate_all for converting all columns to factor

library(dplyr)
df %>%
    mutate_all(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