Graphics Reference
In-Depth Information
# By default, levels are ordered alphabetically
sizes <- factor(c( "small" , "large" , "large" , "small" , "medium" ))
small large large small medium
Levels: large medium small
levels(sizes)[ 1 ] <- "L"
sizes
small L L small medium
Levels: L medium small
# Rename all levels at once
levels(sizes) <- c( "L" , "M" , "S" )
sizes
[ 1 ] S L L S M
Levels: L M S
It's safer to rename factor levels by name rather than by position, since you will be less likely to
make a mistake (and mistakes here may be hard to detect). Also, if your input data set changes
to have more (or fewer) levels, the numeric positions of the existing levels could change, which
could cause serious but nonobvious problems for your analysis.
See Also
If, instead of a factor, you have a character vector with items to rename, see Changing the Names
of Items in a Character Vector .
Removing Unused Levels from a Factor
Problem
You want to remove unused levels from a factor.
Solution
Sometimes, after processing your data you will have a factor that contains levels that are no
longer used. Here's an example:
sizes <- factor(c( "small" , "large" , "large" , "small" , "medium" ))
sizes <- sizes[ 1 : 3 ]
sizes
Search WWH ::




Custom Search