View source: R/01_data_cleaning.R
as.numfactor | R Documentation |
Automatically convert the input x (factor)
into a numeric
vector while keeping the
exact value of x
.
as.numfactor(x)
x |
A |
In R, numeric factors should be coded as character
but it is rarely the
case because most functions actually prefer factors
. It's one of the shortcomings of R.
Consequently, there is no R function that converts a numeric factor (e.g. a binary
variable with only zeros and ones) into a numeric
vector while keeping the correct value (if you use
as.numeric(myfactor)
, you will get the underlying level codes, not the values as numbers), hence the
usefulness of as.numfactor
.
A numeric
vector.
f <- as.factor(cars$speed)
as.numeric(f) # Converts the values into level ranks.
as.numfactor(f) # Works!
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.