| to_character {sjmisc} | R Documentation |
This function converts (replaces) variable values (also of factors
or character vectors) with their associated value labels and returns
them as character vector. This is just a convenient wrapper for
as.character(to_label(x)).
to_character(x, ..., add.non.labelled = FALSE, prefix = FALSE, var.label = NULL, drop.na = TRUE, drop.levels = FALSE)
x |
A vector or data frame. |
... |
Optional, unquoted names of variables that should be selected for
further processing. Required, if |
add.non.labelled |
Logical, if |
prefix |
Logical, if |
var.label |
Optional string, to set variable label attribute for the
returned variable (see vignette Labelled Data and the sjlabelled-Package).
If |
drop.na |
Logical, if |
drop.levels |
Logical, if |
A character vector with the associated value labels as values. If x
is a data frame, the complete data frame x will be returned,
where variables specified in ... are coerced
to character variables;
if ... is not specified, applies to all variables in the
data frame.
Value labels will be removed when converting variables to factors,
variable labels, however, are preserved.
This function is kept for backwards-compatibility. It is preferred to
use as_character.
library(sjlabelled)
data(efc)
print(get_labels(efc)['c161sex'])
head(efc$c161sex)
head(to_character(efc$c161sex))
print(get_labels(efc)['e42dep'])
table(efc$e42dep)
table(to_character(efc$e42dep))
head(efc$e42dep)
head(to_character(efc$e42dep))
# numeric values w/o value labels will also be converted into character
str(efc$e17age)
str(to_character(efc$e17age))
# factor with non-numeric levels, non-prefixed and prefixed
x <- factor(c("a", "b", "c"))
x <- set_labels(x, labels = c("ape", "bear", "cat"))
to_character(x, prefix = FALSE)
to_character(x, prefix = TRUE)
# create vector
x <- c(1, 2, 3, 2, 4, NA)
# add less labels than values
x <- set_labels(x,
labels = c("yes", "maybe", "no"),
force.labels = FALSE,
force.values = FALSE)
# convert to character w/o non-labelled values
to_character(x)
# convert to character, including non-labelled values
to_character(x, add.non.labelled = TRUE)
# create labelled integer, with missing flag
library(haven)
x <- labelled(c(1:3, tagged_na("a", "c", "z"), 4:1, 2:3),
c("Agreement" = 1, "Disagreement" = 4, "First" = tagged_na("c"),
"Refused" = tagged_na("a"), "Not home" = tagged_na("z")))
# to character, with missing labels
to_character(x, drop.na = FALSE)
# to character, missings removed
to_character(x, drop.na = TRUE)
# keep missings, and use non-labelled values as well
to_character(x, add.non.labelled = TRUE, drop.na = FALSE)
# easily coerce specific variables in a data frame to character
# and keep other variables, with their class preserved
to_character(efc, e42dep, e16sex, c172code)