fct_relevel: Reorder factor levels by hand

Description Usage Arguments Examples

View source: R/relevel.R

Description

This is a generalisaton of stats::relevel() that allows you to move any number of levels to any location.

Usage

1
fct_relevel(.f, ..., after = 0L)

Arguments

.f

A factor (or character vector).

...

Character vector of levels. Any levels not mentioned will be left in existing order, after the explicitly mentioned levels. Supports tidy dots.

after

Where should the new values be placed?

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
f <- factor(c("a", "b", "c", "d"))
fct_relevel(f)
fct_relevel(f, "c")
fct_relevel(f, "b", "a")

# Move to the third position
fct_relevel(f, "a", after = 2)

# Relevel to the end
fct_relevel(f, "a", after = Inf)
fct_relevel(f, "a", after = 3)

# Using 'Inf' allows you to relevel to the end when the number
# of levels is unknown or variable (e.g. vectorised operations)
df  <- forcats::gss_cat[, c("rincome", "denom")]
lapply(df, levels)

df2 <- lapply(df, fct_relevel, "Don't know", after = Inf)
lapply(df2, levels)

# You'll get a warning if the levels don't exist
fct_relevel(f, "e")

tidyverse/forcats documentation built on Jan. 11, 2019, 11:10 a.m.