fac2num: Convert factor variable to numeric

View source: R/utility_functions.R

fac2numR Documentation

Convert factor variable to numeric

Description

Convert factor variable with numbers as levels into a numeric variable

Usage

fac2num(x)

Arguments

x

a factor variable with numbers as levels

Details

For example, a factor with levels c("5","7") is converted into a numeric variable with values c(5,7).

Value

A numeric vector based on the levels of x.

Source

Stackoverflow thread

See Also

⁠[robust_values]⁠

Examples

## this is often not intended
as.numeric(factor(c(5,7))) ## result: c(1,2)
## but this
fac2num(factor(c(5,7))) ## result: c(5,7)

## however
as.numeric(factor(c("5","7","a"))) ## 1:3

suppressWarnings(
  fac2num(factor(c("5","7","a"))) ## c(5,7,NA)
)



popEpi documentation built on April 4, 2025, 2:51 a.m.