Learn R Programming

sjmisc (version 1.0.2)

to_value: Converts factors to numeric variables

Description

This function converts (replaces) factor values with the related factor level index number, thus the factor is converted to a numeric variable.

Usage

to_value(x, startAt = NULL, keep.labels = TRUE)

Arguments

x
A (factor) variable or a data frame with (factor) variables.
startAt
the starting index, i.e. the lowest numeric value of the variable's value range. By default, this parameter is NULL, hence the lowest value of the returned numeric variable corresponds to the lowest factor level (if factor is
keep.labels
logical, if TRUE, former factor levels will be attached as value labels. See set_val_labels for more details.

Value

  • A numeric variable with values ranging either from startAt to startAt + length of factor levels, or to the corresponding factor levels (if these were numeric). Or a data frame with numeric variables, if x was a data frame.

See Also

to_label to convert a value into a factor with labelled factor levels and to_fac to convert a numeric variable into a factor (and retain labels)

Examples

Run this code
data(efc)
test <- to_label(efc$e42dep)
table(test)

table(to_value(test))
hist(to_value(test, 0))

# set lowest value of new variable
# to "5".
table(to_value(test, 5))

# numeric factor keeps values
dummy <- factor(c("3", "4", "6"))
table(to_value(dummy))

# non-numeric factor is converted to numeric
# starting at 1
dummy <- factor(c("D", "F", "H"))
table(to_value(dummy))

Run the code above in your browser using DataLab