as.numfactor: Convert factor values as exact numeric values

View source: R/01_data_cleaning.R

as.numfactorR Documentation

Convert factor values as exact numeric values

Description

Automatically convert the input x (factor) into a numeric vector while keeping the exact value of x.

Usage

as.numfactor(x)

Arguments

x

A factor variable (may contain NAs).

Details

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.

Value

A numeric vector.

Examples

f <- as.factor(cars$speed)
as.numeric(f) # Converts the values into level ranks.
as.numfactor(f) # Works!

mrelnoob/jk.dusz.tarping documentation built on July 31, 2023, 9:19 a.m.