简体   繁体   中英

R - convert datatype of all columns in a dataframe from character to numeric dynamically

I have around 200 columns in my dataframe. I am looking to convert the columns that has a data type of char into factors and then to levels or integers.

For example , Man becoming 1.

The below code works manually,

as.factor(df$colName1)
as.integer(df$colName1)

But how can we make that check for all columns using a loop and then convert it ?

Thanks.

df <- apply(df,2,function(x){
      if(is.character(x)){
         x <- as.factor(x)
         levels(x) <- 1:length(levels(x))
         return(x)  
      }
})
## I believe that this should work

With tidyverse , the syntax would be

library(tidyverse)
df %>% 
    mutate_if(is.character, funs(as.integer(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