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
     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, so argument names are
     ignored (but this might not be true of its methods).

_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

