R change all columns of type factor to numeric

前端 未结 2 1586
执笔经年
执笔经年 2020-12-13 07:26

I have a data frame that is 100 X 100. There are 30 columns that are factors. Is there a way to switch only factor-type columns to numeric type without affecting the other

相关标签:
2条回答
  • 2020-12-13 07:41

    See R-FAQ 7.10 at cran.r-project.org http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f

    ALWAYS do as.numeric(as.character(some_Factor)) or you will be sorry.

    0 讨论(0)
  • 2020-12-13 07:52

    Applying the wisdom from Carl Witthoft above:

    asNumeric <- function(x) as.numeric(as.character(x))
    factorsNumeric <- function(d) modifyList(d, lapply(d[, sapply(d, is.factor)],   
                                                       asNumeric))
    

    Example:

    d <- data.frame(x=factor(1:3), y=factor(2:4), z=factor(3:5),
                    r=c("a", "b", "c"), stringsAsFactors=FALSE)
    > f <- factorsNumeric(d)
    > class(f$x)
    [1] "numeric"
    > class(f$r)
    [1] "character"
    
    0 讨论(0)
提交回复
热议问题