to_factor: Convert input to a factor.

Description Usage Arguments Details Examples

View source: R/to_factor.R

Description

The base function as.factor is not a generic, but this variant is. By default, to_factor is a wrapper for as.factor. Please note that to_factor differs slightly from as_factor method provided by haven package.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
to_factor(x, ...)

## S3 method for class 'labelled'
to_factor(x, levels = c("labels", "values", "prefixed"),
  ordered = FALSE, nolabel_to_na = FALSE, sort_levels = c("auto", "none",
  "labels", "values"), decreasing = FALSE, drop_unused_labels = FALSE, ...)

## S3 method for class 'data.frame'
to_factor(x, levels = c("labels", "values", "prefixed"),
  ordered = FALSE, nolabel_to_na = FALSE, sort_levels = c("auto", "none",
  "labels", "values"), decreasing = FALSE, labelled_only = TRUE,
  drop_unused_labels = FALSE, ...)

Arguments

x

Object to coerce to a factor.

...

Other arguments passed down to method.

levels

What should be used for the factor levels: the labels, the values or labels prefixed with values?

ordered

TRUE for ordinal factors, FALSE (default) for nominal factors.

nolabel_to_na

Should values with no label be converted to 'NA'?

sort_levels

How the factor levels should be sorted? (see Details)

decreasing

Should levels be sorted in decreasing order?

drop_unused_labels

Should unused value labels be dropped?

labelled_only

for a data.frame, convert only labelled variables to factors?

Details

If some values doesn't have a label, automatic labels will be created, except if nolabel_to_na is TRUE.

If sort_levels == 'values', the levels will be sorted according to the values of x. If sort_levels == 'labels', the levels will be sorted according to labels' names. If sort_levels == 'none', the levels will be in the order the value labels are defined in x. If some labels are automatically created, they will be added at the end. If sort_levels == 'auto', sort_levels == 'none' will be used, except if some values doesn't have a defined label. In such case, sort_levels == 'values' will be applied.

When applied to a data.frame, only labelled vectors are converted by default to a factor. Use labelled_only = FALSE to convert all variables to factors.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
v <- labelled(c(1,2,2,2,3,9,1,3,2,NA), c(yes = 1, no = 3, "don't know" = 9))
to_factor(v)
to_factor(v, nolabel_to_na = TRUE)
to_factor(v, 'p')
to_factor(v, sort_levels = 'v')
to_factor(v, sort_levels = 'n')
to_factor(v, sort_levels = 'l')

x <- labelled(c('H', 'M', 'H', 'L'), c(low = 'L', medium = 'M', high = 'H'))
to_factor(x, ordered = TRUE)

labelled documentation built on May 25, 2018, 1:03 a.m.