Convert data.frame columns from factors to characters

前端 未结 18 1439
时光取名叫无心
时光取名叫无心 2020-11-22 04:43

I have a data frame. Let\'s call him bob:

> head(bob)
                 phenotype                         exclusion
GSM399350 3- 4- 8- 25- 44+         


        
18条回答
  •  醉梦人生
    2020-11-22 05:14

    If you would use data.table package for the operations on data.frame then the problem is not present.

    library(data.table)
    dt = data.table(col1 = c("a","b","c"), col2 = 1:3)
    sapply(dt, class)
    #       col1        col2 
    #"character"   "integer" 
    

    If you have a factor columns in you dataset already and you want to convert them to character you can do the following.

    library(data.table)
    dt = data.table(col1 = factor(c("a","b","c")), col2 = 1:3)
    sapply(dt, class)
    #     col1      col2 
    # "factor" "integer" 
    upd.cols = sapply(dt, is.factor)
    dt[, names(dt)[upd.cols] := lapply(.SD, as.character), .SDcols = upd.cols]
    sapply(dt, class)
    #       col1        col2 
    #"character"   "integer" 
    

提交回复
热议问题