简体   繁体   中英

R change all columns of type factor to numeric

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 columns (without going the loop route)?

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"

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.

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