# levels: Levels Attributes

### Description

`levels` provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.

### Usage

 ```1 2``` ```levels(x) levels(x) <- value ```

### Arguments

 `x` an object, for example a factor. `value` A valid value for `levels(x)`. For the default method, `NULL` or a character vector. For the `factor` method, a vector of character strings with length at least the number of levels of `x`, or a named list specifying how to rename the levels.

### Details

Both the extractor and replacement forms are generic and new methods can be written for them. The most important method for the replacement function is that for `factor`s.

For the factor replacement method, a `NA` in `value` causes that level to be removed from the levels and the elements formerly with that level to be replaced by `NA`.

Note that for a factor, replacing the levels via `levels(x) <- value` is not the same as (and is preferred to) `attr(x, "levels") <- value`.

The replacement function is primitive.

### References

Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole.

`nlevels`, `relevel`, `reorder`.
 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32``` ```## assign individual levels x <- gl(2, 4, 8) levels(x)[1] <- "low" levels(x)[2] <- "high" x ## or as a group y <- gl(2, 4, 8) levels(y) <- c("low", "high") y ## combine some levels z <- gl(3, 2, 12, labels = c("apple", "salad", "orange")) z levels(z) <- c("fruit", "veg", "fruit") z ## same, using a named list z <- gl(3, 2, 12, labels = c("apple", "salad", "orange")) z levels(z) <- list("fruit" = c("apple","orange"), "veg" = "salad") z ## we can add levels this way: f <- factor(c("a","b")) levels(f) <- c("c", "a", "b") f f <- factor(c("a","b")) levels(f) <- list(C = "C", A = "a", B = "b") f ```