asNumericIfPossible {eatTools} | R Documentation |
Convert a Vector, Matrix or Data Frame Into Numeric Values If Possible
Description
This function converts vectors and matrices of all kinds to numeric
. The function can
also be used to convert all columns of a data.frame
to class numeric
for
which this conversion is possible i.e. without creating NA
when it fails.
Non-convertible columns are maintained.
Usage
asNumericIfPossible(x, maintain.factor.scores = TRUE, force.string = TRUE,
transform.factors = TRUE, varName = NULL)
Arguments
x |
A vector or data frame which should be converted. |
maintain.factor.scores |
Logical:
If |
force.string |
Logical indicating whether columns should be force to
numeric, even if NAs are induced.
If |
transform.factors |
Logical indicating whether columns of class
|
varName |
Optional: Name of the corresponding variable. Doesn't have to be changed by user. |
Details
In R, factors may represent ordered categories or categorical variables.
Depending on the meaning of the variable, a conversion of the nominal values
(of a factor variable) to numeric values may be desirable or not. The arguments
transform.factors
and maintain.factor.scores
specify if and how
factor variables should be treated. See examples.
Author(s)
Sebastian Weirich, Karoline Sachse, Benjamin Becker
Examples
dat <- data.frame(X1 = c("1",NA,"0"), X2 = c("a",NA,"b"),
X3 = c(TRUE,FALSE,FALSE), X4 = as.factor(c("a",NA,"b")),
X5 = as.factor(c("5","6","7")), stringsAsFactors = FALSE)
str(dat)
asNumericIfPossible(dat)
asNumericIfPossible(dat, transform.factors=TRUE,
maintain.factor.scores=FALSE)
asNumericIfPossible(dat, transform.factors=TRUE,
maintain.factor.scores=TRUE)