Learn R Programming

REDCapCAST (version 25.3.1)

as_factor: Convert labelled vectors to factors while preserving attributes

Description

This extends as_factor as well as as_factor, by appending original attributes except for "class" after converting to factor to avoid ta loss in case of rich formatted and labelled data.

Usage

as_factor(x, ...)

# S3 method for factor as_factor(x, ...)

# S3 method for logical as_factor(x, ...)

# S3 method for numeric as_factor(x, ...)

# S3 method for character as_factor(x, ...)

# S3 method for haven_labelled as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... )

# S3 method for labelled as_factor( x, levels = c("default", "labels", "values", "both"), ordered = FALSE, ... )

# S3 method for data.frame as_factor(x, ..., only_labelled = TRUE)

Arguments

x

Object to coerce to a factor.

...

Other arguments passed down to method.

levels

How to create the levels of the generated factor:

* "default": uses labels where available, otherwise the values. Labels are sorted by value. * "both": like "default", but pastes together the level and value * "label": use only the labels; unlabelled values become `NA` * "values": use only the values

ordered

If `TRUE` create an ordered (ordinal) factor, if `FALSE` (the default) create a regular (nominal) factor.

only_labelled

Only apply to labelled columns?

Details

Please refer to parent functions for extended documentation. To avoid redundancy calls and errors, functions are copy-pasted here

Empty variables with empty levels attribute are interpreted as logicals

Examples

Run this code
# will preserve all attributes
c(1, 4, 3, "A", 7, 8, 1) |> as_factor()
structure(c(1, 2, 3, 2, 10, 9),
  labels = c(Unknown = 9, Refused = 10)
) |>
  as_factor() |>
  dput()

structure(c(1, 2, 3, 2, 10, 9),
  labels = c(Unknown = 9, Refused = 10),
  class = "haven_labelled"
) |>
  as_factor() |> class()
structure(rep(NA,10),
  class = c("labelled")
) |>
  as_factor() |> summary()

rep(NA,10) |> as_factor()

Run the code above in your browser using DataLab