

switch {base}                                R Documentation

_S_e_l_e_c_t _O_n_e _o_f _a _L_i_s_t _o_f _A_l_t_e_r_n_a_t_i_v_e_s

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

     `switch' evaluates `EXPR'.  If the value is an integer
     between 1 and `nargs()-1' then the corresponding ele-
     ment of `...' is evaluated and the result returned.

     If `EXPR' returns a character string then that string
     is used to match the names of the elements in `...'.
     If there is an exact match then that element is evalu-
     ated and the result returned.  In the case of no match,
     if there's a further argument in `switch(..)'  that one
     is returned, otherwise `NULL'.

_U_s_a_g_e_:

     switch(EXPR, ...)

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

    EXPR: an expression evaluating to a number or a charac-
          ter string.

     ...: the list of alternatives, given explicitly.

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

     centre <- function(x, type) {
       switch(type,
             mean = mean(x),
             median = median(x),
             trimmed = mean(x, trim = .1))
     }
     x <- rcauchy(10)
     centre(x, "mean")
     centre(x, "median")
     centre(x, "trimmed")

     ccc <- c("b","QQ","a","A","b")
     for(ch in ccc) cat(ch,":",switch(ch, a=1, b=2:3),               "\n")
     for(ch in ccc) cat(ch,":",switch(ch, a=1, b=2:3, "Otherwise: last arg."),"\n")

     ## Numeric EXPR don't allow an `otherwise':
     for(i in c(-1:3,9))  print(switch(i, 1,2,3,4))

