Graphics Reference
In-Depth Information
"large" "medium" "small"
# With revalue(), pass it a named vector with the mappings
sizes1
<-
revalue(sizes, c(small
=
"S"
, medium
=
"M"
, large
=
"L"
))
sizes1
S L L S M
Levels: L M S
# Can also use quotes -- useful if there are spaces or other strange characters
revalue(sizes, c(
"small"
=
"S"
,
"medium"
=
"M"
,
"large"
=
"L"
))
# mapvalues() lets you use two separate vectors instead of a named vector
mapvalues(sizes, c(
"small"
,
"medium"
,
"large"
), c(
"S"
,
"M"
,
"L"
))
Discussion
The
revalue()
and
mapvalues()
functions are convenient, but for a more traditional (and
clunky) R method for renaming factor levels, use the
levels()<-
function:
sizes
<-
factor(c(
"small"
,
"large"
,
"large"
,
"small"
,
"medium"
))
# Index into the levels and rename each one
levels(sizes)[levels(sizes)
==
"large"
]
<-
"L"
levels(sizes)[levels(sizes)
==
"medium"
]
<-
"M"
levels(sizes)[levels(sizes)
==
"small"
]
<-
"S"
sizes
S L L S M
Levels: L M S
If you are renaming allyour factor levels, there is a simpler method. You can pass a list to
levels()<-
:
sizes
<-
factor(c(
"small"
,
"large"
,
"large"
,
"small"
,
"medium"
))
levels(sizes)
<-
list(S
=
"small"
, M
=
"medium"
, L
=
"large"
)
sizes
S L L S M
Levels: L M S
With this method, all factor levels must be specified in the list; if any are missing, they will be
replaced with
NA
.
It's also possible to rename factor levels by position, but this is somewhat inelegant: