Learn R Programming

sjmisc (version 1.2)

to_label: Convert variable into factor and replaces values with associated value labels

Description

This function converts (replaces) variable values (also of factors) with their associated value labels. Might be helpful for factor variables. For instance, if you have a Gender variable with 0/1 value, and associated labels are male/female, this function would convert all 0 to male and all 1 to female and returns the new variable as factor.

Usage

to_label(x, add.non.labelled = FALSE, drop.na = TRUE)

Arguments

x
variable of type numeric, atomic, factor or labelled
add.non.labelled
logical, if TRUE, values without associated value label will also be converted to labels (as is). See 'Examples'.
drop.na
logical, if TRUE, all types of missing value codes are converted into NA before x is converted as factor. If FALSE, missing values will be left as their original codes. See 'Examples' and

Value

  • A factor variable with the associated value labels as factor levels, or a data frame with such factor variables (if x was a data frame).

Details

See 'Details' in get_na.

See Also

to_factor to convert a numeric variable into a factor (and preserve labels) and to_value to convert a factor into a numeric variable.

Examples

Run this code
data(efc)
print(get_labels(efc)['c161sex'])
head(efc$c161sex)
head(to_label(efc$c161sex))

print(get_labels(efc)['e42dep'])
table(efc$e42dep)
table(to_label(efc$e42dep))

head(efc$e42dep)
head(to_label(efc$e42dep))

# structure of numeric values won't be changed
# by this function, it only applies to labelled vectors
# (typically categorical or factor variables)
str(efc$e17age)
str(to_label(efc$e17age))

# factor with non-numeric levels won't be changed, either,
# however, a warning is produced
to_label(factor(c("a", "b", "c")))

# create vector
x <- c(1, 2, 3, 2, 4, NA)
# add less labels than values
x <- set_labels(x, c("yes", "maybe", "no"),
                force.labels = FALSE,
                force.values = FALSE)
# convert to label w/o non-labelled values
to_label(x)
# convert to label, including non-labelled values
to_label(x, add.non.labelled = TRUE)


# create labelled integer, with missing flag
x <- labelled(c(1, 2, 1, 3, 4, 1),
              c(Male = 1, Female = 2, Refused = 3, "N/A" = 4),
              c(FALSE, FALSE, TRUE, TRUE))
# to labelled factor, with missing labels
to_label(x, drop.na = FALSE)
# to labelled factor, missings removed
to_label(x, drop.na = TRUE)

Run the code above in your browser using DataLab