Relevel | R Documentation |
The levels of a factor are re-ordered so that the levels specified by
ref
appear first and remaining levels are moved down. This is
useful for contr.treatment
contrasts which take the first level
as the reference. Factor levels may also be combined; two possibilities for
specifying this are supported: hard coding or table look-up.
## S3 method for class 'factor'
Relevel( x, ref, first = TRUE, collapse="+",
xlevels=TRUE, nogroup=TRUE, ... )
x |
A(n unordered) factor |
ref |
Vector, list or data frame, array, matrix or table. If If If |
first |
Should the levels mentioned in |
collapse |
String used when constructing names for combined factor levels. |
xlevels |
Logical. Should all levels in the 2nd column of
|
nogroup |
Logical. Should levels present in the input but not in
the 1st column of |
... |
Arguments passed on to other methods. |
The facility where ref
is a two-column matrix mimics the
SAS-facility of formats where a dataset can be used to construct a
format — SAS format is the grouping tool for variable
values.
If ref
is a two-column object and ref[,2]
is a factor
Relevel
will preserve the order of levels from ref[,2]
.
An unordered factor, where levels of x
have been reordered
and/or collapsed.
Bendix Carstensen http://bendixcarstensen.com, Lars Jorge Diaz
Relevel.Lexis
# Grouping using a list (hard coding)
#
ff <- factor(sample(letters[1:5], 100, replace = TRUE))
table( ff, Relevel(ff, list( AB = 1:2, "Dee" = 4, c(3,5))))
table( ff, Relevel(ff,
list( 5:4, Z = c("c", "a") ),
coll = "-und-",
first = FALSE ) )
## Grouping using a two-column matrix as input:
## A factor with levels to be grouped together
ff <- factor(c("Bear","Bear","Crocodile","Snake","Crocodile","Bear"))
ff
## A grouping table
(gg <- data.frame(Animal = c("Bear","Whale","Crocodile","Snake","Eagle"),
Class = c("Mammal","Mammal","Reptile","Reptile","Bird")))
str(gg)
Relevel(ff, gg, xlevels = FALSE)
Relevel(ff, gg )
Relevel(ff, gg[c(1:5,5:1),])
## This crashes with an error
(GG <- rbind( gg, c("Bear","Reptile")))
try(Relevel(ff, GG))
ff <- factor(c(as.character(ff), "Jellyfish", "Spider"))
Relevel(ff, gg)
# excludes non-occupied levels
Relevel(ff, gg, xlevels = FALSE)
# If you do not want unknown animals classified, this returns NAs:
Relevel(ff, gg, nogroup = FALSE)
# Both
Relevel(ff, gg, nogroup = FALSE, xlevels = FALSE)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.