factor_to_numeric: Convert a factor to a numeric vector using its levels

View source: R/utils.R

factor_to_numericR Documentation

Convert a factor to a numeric vector using its levels

Description

Converts to a numeric vector factors with levels that could be appropriately converted to numeric values (either number or logical-type strings).

Usage

factor_to_numeric(x)

Arguments

x

A factor.

Details

The output from the obvious as.numeric() is unlikely to be what is desired, since it acts on the underlying integers, rather than the levels. This function instead uses as.integer(as.logical(x)) to attempt to coerce the character levels. If all levels are strings that would be coercible by as.logical(), that is in c("T", "TRUE", "True", "true", "F", "FALSE", "False", "false", NA), then they are converted appropriately to a numeric vector instead. The two methods are never mixed, so factor_to_numeric(factor(c("T", "1"))) will attempt numeric conversion and produce NA for the "T".

Examples

x <- factor(3:5)
as.numeric(x)
factor_to_numeric(x)
factor_to_numeric(factor(c("T", "false", NA)))

jedwards24/edwards documentation built on Sept. 2, 2023, 8:16 a.m.