Learn R Programming

sjmisc (version 1.5)

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, ref.lvl = NULL)

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

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
ref.lvl
Numeric, specifies the reference level for the new factor. Use this parameter if a different factor level than the lowest value should be used as reference level. If NULL, lowest value will become the reference level. See

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)


# Convert to factor, using different reference level
x <- to_factor(efc$e42dep)
str(x)
table(x)

x <- to_factor(efc$e42dep, ref.lvl = 3)
str(x)
table(x)

Run the code above in your browser using DataLab