Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 563
screechOwl Avatar asked Dec 21 '11 21:12

screechOwl


People also ask

How do I convert multiple factor columns to numeric in R?

Use the lapply() Function to Convert Multiple Columns From Integer to Numeric Type in R. Base R's lapply() function allows us to apply a function to elements of a list. We will apply the as. numeric() function.

How do you make all columns Numeric in R?

To convert all the columns of the data frame to numeric in R, use the lapply() function to loop over the columns and convert to numeric by first converting it to character class as the columns were a factor.

How do I convert factor to numeric in R?

We must first convert the factor vector to a character vector, then to a numeric vector. This ensures that the numeric vector contains the actual numeric values instead of the factor levels.


2 Answers

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"
like image 70
David F Avatar answered Oct 04 '22 15:10

David F


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.

like image 29
Carl Witthoft Avatar answered Oct 04 '22 14:10

Carl Witthoft