Learn R Programming

sjmisc (version 2.0.1)

to_factor: Convert variable into factor and keep value labels

Description

This function converts a variable into a factor, but preserves variable and value label attributes. See 'Examples'.

Usage

to_factor(x, add.non.labelled = FALSE, ref.lvl = NULL)

Arguments

x
Numeric, atomic or character vector or a data frame with such vectors.
add.non.labelled
Logical, if TRUE, non-labelled values also get value labels.
ref.lvl
Numeric, specifies the reference level for the new factor. Use this parameter if a different factor level than the lowest value should be used as reference level. If NULL, lowest value will become the reference level. See ref_lvl for details.

Value

A factor variable, including variable and value labels, respectively a data frame with factor variables (including variable and value labels) if x was a data frame.

Details

to_factor converts numeric values into a factor with numeric levels. to_label, however, converts a vector into a factor and uses value labels as factor levels. Furthermore, see 'Details' in get_na.

See Also

to_value to convert a factor into a numeric value and to_label to convert a value into a factor with labelled factor levels.

Examples

Run this code
data(efc)
# normal factor conversion, loses value attributes
x <- as.factor(efc$e42dep)
frq(x)

# factor conversion, which keeps value attributes
x <- to_factor(efc$e42dep)
frq(x)

# create parially labelled vector
x <- set_labels(efc$e42dep, c(`1` = "independent", `4` = "severe dependency",
                              `9` = "missing value"))

# only copy existing value labels
to_factor(x)
get_labels(to_factor(x), include.values = "p")

# also add labels to non-labelled values
to_factor(x, add.non.labelled = TRUE)
get_labels(to_factor(x, add.non.labelled = TRUE), include.values = "p")

# Convert to factor, using different reference level
x <- to_factor(efc$e42dep)
str(x)
table(x)

x <- to_factor(efc$e42dep, ref.lvl = 3)
str(x)
table(x)

Run the code above in your browser using DataLab