Learn R Programming

mariposa (version 0.7.3)

to_labelled: Convert Variables to Labelled Format

Description

Converts factors, character vectors, or plain numeric vectors to haven_labelled class, optionally assigning value labels and a variable label. This is the reverse of to_label().

Usage

to_labelled(data, ..., labels = NULL, label = NULL)

Value

The input with variables converted to haven_labelled. For single vector input, returns a haven_labelled vector.

Arguments

data

A data frame, tibble, or a single vector.

...

Optional: unquoted variable names (tidyselect supported). If empty on a data frame, converts all factor columns.

labels

Optional: a named numeric vector of value labels to assign. If NULL and the input is a factor, factor levels are used as labels.

label

Optional: a variable label string.

Details

Factor Conversion

When converting a factor, the integer codes (1, 2, 3, ...) become the numeric values and the factor levels become the value labels.

Character Conversion

Character vectors are converted to numeric (sequential integers) with the unique character values as labels.

See Also

to_label() for the reverse operation, val_labels() for setting labels on existing labelled vectors

Other labels: copy_labels(), drop_labels(), find_var(), set_na(), to_character(), to_label(), to_numeric(), unlabel(), val_labels(), var_label()

Examples

Run this code
# Factor -> haven_labelled
x <- factor(c("Male", "Female", "Male"))
to_labelled(x)

# Numeric with custom labels
to_labelled(c(1, 2, 3),
  labels = c("Low" = 1, "Medium" = 2, "High" = 3),
  label = "Satisfaction level"
)

# All factors in a data frame
data <- to_labelled(survey_data)

Run the code above in your browser using DataLab