Learn R Programming

sjmisc (version 1.2)

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, drop.na = TRUE)

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

Arguments

x
numeric or atomic variable or a data frame with numeric or atomic variables.
add.non.labelled
logical, if TRUE, non-labelled values also get value labels.
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, including variable and value labels, respectively a data frame with factor variables (including variable and value labels) if x was a data frame.

Details

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)
library(sjPlot)
# normal factor conversion, loses value attributes
efc$e42dep <- as.factor(efc$e42dep)
sjt.frq(efc$e42dep)

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

data(efc)
# 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")

# 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 factor, with missing labels
to_factor(x, drop.na = FALSE)
# to factor, missings removed
to_factor(x, drop.na = TRUE)

Run the code above in your browser using DataLab