# NOT RUN {
data(efc)
print(get_labels(efc)['c161sex'])
head(efc$c161sex)
head(as_label(efc$c161sex))
print(get_labels(efc)['e42dep'])
table(efc$e42dep)
table(as_label(efc$e42dep))
head(efc$e42dep)
head(as_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(as_label(efc$e17age))
# factor with non-numeric levels
as_label(factor(c("a", "b", "c")))
# factor with non-numeric levels, prefixed
x <- factor(c("a", "b", "c"))
x <- set_labels(x, labels = c("ape", "bear", "cat"))
as_label(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 label w/o non-labelled values
as_label(x)
# convert to label, including non-labelled values
as_label(x, add.non.labelled = TRUE)
# create labelled integer, with missing flag
if (require("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 labelled factor, with missing labels
as_label(x, drop.na = FALSE)
# to labelled factor, missings removed
as_label(x, drop.na = TRUE)
# keep missings, and use non-labelled values as well
as_label(x, add.non.labelled = TRUE, drop.na = FALSE)
}
# convert labelled character to factor
dummy <- c("M", "F", "F", "X")
dummy <- set_labels(
dummy,
labels = c(`M` = "Male", `F` = "Female", `X` = "Refused")
)
get_labels(dummy,, "p")
as_label(dummy)
# drop unused factor levels, but preserve variable label
x <- factor(c("a", "b", "c"), levels = c("a", "b", "c", "d"))
x <- set_labels(x, labels = c("ape", "bear", "cat"))
set_label(x) <- "A factor!"
x
as_label(x, drop.levels = TRUE)
# change variable label
as_label(x, var.label = "New variable label!", drop.levels = TRUE)
# convert to numeric and back again, preserving label attributes
# *and* values in numeric vector
x <- c(0, 1, 0, 4)
x <- set_labels(x, labels = c(`null` = 0, `one` = 1, `four` = 4))
# to factor
as_label(x)
# to factor, back to numeric - values are 1, 2 and 3,
# instead of original 0, 1 and 4
as_numeric(as_label(x))
# preserve label-attributes when converting to factor, use these attributes
# to restore original numeric values when converting back to numeric
as_numeric(as_label(x, keep.labels = TRUE), use.labels = TRUE)
# easily coerce specific variables in a data frame to factor
# and keep other variables, with their class preserved
as_label(efc, e42dep, e16sex, c172code)
# }
Run the code above in your browser using DataLab