Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

as_factor

Convert input to a factor.


Description

The base function as.factor() is not a generic, but this variant is. Methods are provided for factors, character vectors, labelled vectors, and data frames. By default, when applied to a data frame, it only affects labelled columns.

Usage

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

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

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

Arguments

x

Object to coerce to a factor.

...

Other arguments passed down to method.

only_labelled

Only apply to labelled columns?

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.

Details

Includes methods for both class haven_labelled and labelled for backward compatibility.

Examples

x <- labelled(sample(5, 10, replace = TRUE), c(Bad = 1, Good = 5))

# Default method uses values where available
as_factor(x)
# You can also extract just the labels
as_factor(x, levels = "labels")
# Or just the values
as_factor(x, levels = "values")
# Or combine value and label
as_factor(x, levels = "both")

# as_factor() will preserve SPSS missing values from values and ranges
y <- labelled_spss(1:10, na_values = c(2, 4), na_range = c(8, 10))
as_factor(y)
# use zap_missing() first to convert to NAs
zap_missing(y)
as_factor(zap_missing(y))

haven

Import and Export 'SPSS', 'Stata' and 'SAS' Files

v2.4.1
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre], Evan Miller [aut, cph] (Author of included ReadStat code), RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.