Learn R Programming

sjmisc (version 1.2)

to_value: Convert 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, start.at = NULL, keep.labels = TRUE, startAt)

Arguments

x
factor or a data frame with factors
start.at
starting index, i.e. the lowest numeric value of the variable's value range. By default, this argument 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 added as value labels. See set_labels for more details.
startAt
deprecated; use start.at instead

Value

  • A numeric variable with values ranging either from start.at to start.at + 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 labelled vector into a factor with labelled factor levels and to_factor to convert a numeric variable into a factor (and preserve 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))

# do not drop unused factor levels
dummy <- ordered(c(rep("No", 5), rep("Maybe", 3)),
                 levels = c("Yes", "No", "Maybe"))
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