Convert factor to integer
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))
.
Jeff Erickson
Staff Software Engineer, Services at Daily Harvest.
Updated on June 04, 2020Comments
-
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, andas.integer()
oras.numeric()
will convert it to the number that system is storing that factor as, which is not helpful.Thank you!
Jeff
-
Jeff Erickson over 13 yearsI tried this, but I get the warning message: "NAs introduced by coercion." What does this mean?
-
Jeff Erickson over 13 yearsOr does this just mean that some of them were not numbers to start with?
-
Gavin Simpson over 13 years@Jeff it means that some of the characters aren't numbers, so they get converted to
NA
when you useas.numeric(....)
. Look atlevels(fac)
andas.numeric(levels(fac))
replacingfac
with your factor variable to see which are being coerced toNA
. -
davsjob over 5 yearsyou can use convert() from hablar to do this.
df %>% convert(num(column_name))
to safely coerce from factor to numerical