R change all columns of type factor to numeric

前端 未结 2 1589
执笔经年
执笔经年 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: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"
    

提交回复
热议问题