Convert factor to integer

RIntegerCoercion

R Problem Overview


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

R Solutions


Solution 1 - R

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

Solution 2 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff EricksonView Question on Stackoverflow
Solution 1 - RAaron left Stack OverflowView Answer on Stackoverflow
Solution 2 - RGavin SimpsonView Answer on Stackoverflow