levels                 package:base                 R Documentation

_L_e_v_e_l_s _A_t_t_r_i_b_u_t_e_s

_D_e_s_c_r_i_p_t_i_o_n:

     '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.

_U_s_a_g_e:

     levels(x)
     levels(x) <- value

_A_r_g_u_m_e_n_t_s:

       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.

_D_e_t_a_i_l_s:

     Both the extractor and replacement forms are generic and new
     methods can be written for them. The most important method for the
     replacment 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'.

_R_e_f_e_r_e_n_c_e_s:

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

_S_e_e _A_l_s_o:

     'nlevels', 'relevel', 'reorder'.

_E_x_a_m_p_l_e_s:

     ## 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)
     levels(z) <- c("A", "B", "A")
     z

     ## same, using a named list
     z <- gl(3, 2, 12)
     levels(z) <- list(A=c(1,3), B=2)
     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

