factor_to_numeric | R Documentation |
Converts to a numeric vector factors with levels that could be appropriately converted to numeric values (either number or logical-type strings).
factor_to_numeric(x)
x |
A factor. |
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"
.
x <- factor(3:5)
as.numeric(x)
factor_to_numeric(x)
factor_to_numeric(factor(c("T", "false", NA)))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.