refactor: Factors, Redux

Description Usage Arguments Value See Also Examples

Description

Factors, Redux

Usage

1
refactor(x, levels = NULL, logic = c("freq", "appear"), ...)

Arguments

x

A vector of data.

levels

An optional character vector to be used as the levels. If specified, x, levels, and additional arguments via ... are passed through to factor.

logic

The logical principle by which levels of x should be set. If freq (the default), the levels are in order of decreasing frequency, with ties broken alphabetically. If appear, the levels are in order of appearance.

...

Additional arguments for base::factor(), e.g. ordered.

Value

A factor.

See Also

factor

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
set.seed(1)
x <- sample(letters, size = 20, replace = TRUE)

if (requireNamespace("ggplot2")) {
  library(ggplot2)

  ## refactor on-the-fly to get ggplot2 barplot sorted by frequency
  ggplot(data.frame(x = refactor(x)), aes(x)) + geom_bar()

  ## or create the factor explicitly
  xfact <- refactor(x)
  ggplot(data.frame(x = xfact), aes(x)) + geom_bar()

  ## set levels in order of appearance in the data
  xfact_appear <- refactor(x, logic = "appear")
  ggplot(data.frame(x = xfact_appear), aes(x)) + geom_bar()
}

jennybc/refactor documentation built on May 19, 2019, 5:05 a.m.