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
|
|
|
|
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
|
|
|
|
Combine factors
|
factor(c(as.character(x), as.character(y)), union(levels(x), levels(y)))
|
|
Test
| Action |
Code |
Details |
|
Is factor
|
|
|
|
Contains value v
|
|
|
Contains NA value (not as level)
|
|
|
Contains NA (as <NA> level)
|
|
anyNA(f) does not work! |
|
Contains level named v
|
|
|
Contains <NA> level
|
|
|
| Action |
Code |
Details |
|
Levels
|
|
|
|
Number of levels
|
|
|
|
Levels, as factor, and in order
|
factor(levels(f), levels(f))
|
|
|
Used levels, as factor, and in order
|
|
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
|
|
|
|
Add NA as a factor level if needed (NAs present)
|
f = addNA(f, ifany = TRUE)
|
|
|
Drop specific factor levels
|
|
|
|
Drop factor levels except specific
|
|
|
|
Drop unused factors levels
|
|
|
Shrink
| Action |
Code |
Details |
|
Subset, drop unused levels
|
|
|
Grow
Join
| Action |
Code |
Details |
|
Combine factors
|
|
Resulting factor has levels that are a union of the original levels |
Convert
| Action |
Code |
Details |
|
To vector of strings
|
|
|
|
To vector of level indices
|
|
|
|
To vector of level indices
|
|
|
|
To ordered factor
|
|
|