Skip to content
Incomplete sheet

This sheet is incomplete and could use some attention. Please submit code snippet suggestions as an issue or PR here.

factor

For representing categorical data with a finite number of options (levels)

Create

Action Code Details
From vector
factor(x)
From vector, with renamed levels
factor(x, levels=1:3, labels=LETTERS[1:3]
Generate by pattern
gl(5, 2, labels=LETTERS[1:5])
Generate factor of interactions with another
interaction(f1, f2)
Combine factors
factor(c(as.character(x), as.character(y)), union(levels(x), levels(y)))

Test

Action Code Details
Is factor
is.factor(x)
Contains value v
v %in% f
Contains NA value (not as level)
anyNA(f)
Contains NA (as <NA> level)
NA %in% f
anyNA(f) does not work!
Contains level named v
v %in% levels(f)
Contains <NA> level
anyNA(levels(f))

Extract

Action Code Details
Levels
levels(f)
Number of levels
nlevels(f)
Levels, as factor, and in order
factor(levels(f), levels(f))
Used levels, as factor, and in order
sort(unique(f))
Useful for generating reference categorical newdata for predict()

Derive

Action Code Details
Remap categories / values
x = factor(c('a1', 'b1', 'a2', 'c1'))
factor(x, levels=levels(x), labels=c('a', 'a', 'b', 'c'))

Alter levels

Action Code Details
Add NA as a factor level
f = addNA(f)
Add NA as a factor level if needed (NAs present)
f = addNA(f, ifany = TRUE)
Drop specific factor levels
droplevels(f, exclude=X)
Drop factor levels except specific
droplevels(f, except=X)
Drop unused factors levels
factor(f)

Shrink

Action Code Details
Subset, drop unused levels
f[1:2, drop=TRUE]

Grow

Join

Action Code Details
Combine factors
c(x, y)
Resulting factor has levels that are a union of the original levels

Convert

Action Code Details
To vector of strings
as.character(x)
To vector of level indices
as.numeric(x)
To vector of level indices
as.integer(x)
To ordered factor
as.ordered(x)