This function converts a variable into a factor, but preserves variable and value label attributes.

as_factor(x, ...)

to_factor(x, ...)

# S3 method for data.frame
as_factor(x, ..., add.non.labelled = FALSE)

Arguments

x

A vector or data frame.

...

Optional, unquoted names of variables that should be selected for further processing. Required, if x is a data frame (and no vector) and only selected variables from x should be processed. You may also use functions like : or tidyselect's select-helpers. See 'Examples'.

add.non.labelled

Logical, if TRUE, non-labelled values also get value labels.

Value

A factor, including variable and value labels. If x is a data frame, the complete data frame x will be returned, where variables specified in ... are coerced to factors (including variable and value labels); if ... is not specified, applies to all variables in the data frame.

Details

as_factor converts numeric values into a factor with numeric levels. as_label, however, converts a vector into a factor and uses value labels as factor levels.

Note

This function is intended for use with vectors that have value and variable label attributes. Unlike as.factor, as_factor converts a variable into a factor and preserves the value and variable label attributes.

Adding label attributes is automatically done by importing data sets with one of the read_*-functions, like read_spss. Else, value and variable labels can be manually added to vectors with set_labels and set_label.

Examples

if (require("sjmisc") && require("magrittr")) {
  data(efc)
  # normal factor conversion, loses value attributes
  x <- as.factor(efc$e42dep)
  frq(x)

  # factor conversion, which keeps value attributes
  x <- as_factor(efc$e42dep)
  frq(x)

  # create partially labelled vector
  x <- set_labels(
    efc$e42dep,
    labels = c(
      `1` = "independent",
      `4` = "severe dependency",
      `9` = "missing value"
   ))

  # only copy existing value labels
  as_factor(x) %>% head()
  get_labels(as_factor(x), values = "p")

  # also add labels to non-labelled values
  as_factor(x, add.non.labelled = TRUE) %>% head()
  get_labels(as_factor(x, add.non.labelled = TRUE), values = "p")


  # easily coerce specific variables in a data frame to factor
  # and keep other variables, with their class preserved
  as_factor(efc, e42dep, e16sex, c172code) %>% head()

  # use select-helpers from dplyr-package
  if (require("dplyr")) {
    as_factor(efc, contains("cop"), c161sex:c175empl) %>% head()
  }
}
#> Loading required package: sjmisc
#> Loading required package: magrittr
#> Error: 1 components of `...` were not used.
#> 
#> We detected these problematic arguments:
#> * `add.non.labelled`
#> 
#> Did you misspecify an argument?