levels
Get Or Set Levels Attribute

Description

Returns the levels of an object, or sets the levels attribute for an object. This is most useful for factors. This function is implemented as an S3 method.

Usage

levels(x) 
levels(x) <- value

Arguments

x any object. Typically a factor.
value a vector of character strings containing the new levels to set. If the new levels in value are not unique, they are transformed into the unique new levels. If the new levels contain exists, it is removed from the new levels. This can change the numeric values of the factor.

Details

Using levels<- ensures that the length of value is the same as the length of the (old) levels of x, but you can combine factors by giving them the same level.
value<- can be a list.
Value
returns the levels if x has levels; otherwise returns NULL.
See Also
factor, ordered, nlevels
Examples
levels(Sdatasets::fuel.frame$Type[1:9])
## [1] "Compact" "Large"   "Medium"  "Small"   "Sporty"  "Van"

# demonstrates drop: levels(Sdatasets::fuel.frame$Type[1:9, drop=TRUE]) ## [1] "Small"

fac <- factor(c("1", "2", "3", "4")) levels(fac) ## [1] "1" "2" "3" "4" ## Not run: levels(fac) <- c("1", "2", "3") ## Error in `levels<-.factor`(`*tmp*`, value = c("1", "2", "3")) : ## number of levels differs ## End(Not run)

levels(fac) <- c("1", "2", "3", "a", "b") fac ## [1] 1 2 3 a ## Levels: 1 2 3 a b

## Not run: v <- list(c("1", "2", "3")) levels(fac) <- v ## Error in `levels<-.factor`(fac) : replacement has length zero ## End(Not run)

v <- list(a=c("1"), b=c("2"), c=("3")) levels(fac) <- v fac ## [1] a b c a ## Levels: a b c

Package base version 4.0.0-28
Package Index