Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert factor to integer [duplicate]

I am manipulating a data frame using the reshape package. When using the melt function, it factorizes my value column, which is a problem because a subset of those values are integers that I want to be able to perform operations on.

Does anyone know of a way to coerce a factor into an integer? Using as.character() will convert it to the correct character, but then I cannot immediately perform an operation on it, and as.integer() or as.numeric() will convert it to the number that system is storing that factor as, which is not helpful.

Thank you!

Jeff

like image 293
Jeff Erickson Avatar asked Jan 25 '11 20:01

Jeff Erickson


People also ask

How do you change a factor into a numeric?

There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as. numeric().

How do I convert a factor to a numeric in a Dataframe 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.

How do I change a vector to numeric in R?

To convert a character vector to a numeric vector, use as. numeric(). It is important to do this before using the vector in any statistical functions, since the default behavior in R is to convert character vectors to factors. Be careful that there are no characters included in any strings, since as.

How do I convert an integer to a factor in R?

To convert the data type of all columns from integer to factor, we can use lapply function with factor function.


2 Answers

Quoting directly from the help page for factor:

To transform a factor f to its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

like image 143
Aaron left Stack Overflow Avatar answered Oct 19 '22 22:10

Aaron left Stack Overflow


You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2")) > as.numeric(as.character(fac)) [1] 1 2 1 2 
like image 40
Gavin Simpson Avatar answered Oct 19 '22 23:10

Gavin Simpson