Convert factor to integer

161,343

Solution 1

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

Solution 2

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

Share:
161,343
Jeff Erickson
Author by

Jeff Erickson

Staff Software Engineer, Services at Daily Harvest.

Updated on June 04, 2020

Comments

  • Jeff Erickson
    Jeff Erickson almost 4 years

    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

  • Jeff Erickson
    Jeff Erickson over 13 years
    I tried this, but I get the warning message: "NAs introduced by coercion." What does this mean?
  • Jeff Erickson
    Jeff Erickson over 13 years
    Or does this just mean that some of them were not numbers to start with?
  • Gavin Simpson
    Gavin Simpson over 13 years
    @Jeff it means that some of the characters aren't numbers, so they get converted to NA when you use as.numeric(....). Look at levels(fac) and as.numeric(levels(fac)) replacing fac with your factor variable to see which are being coerced to NA.
  • davsjob
    davsjob over 5 years
    you can use convert() from hablar to do this. df %>% convert(num(column_name)) to safely coerce from factor to numerical