levels(x) levels(x) <- value
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. |
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