switch                 package: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' and accordingly chooses one of the
     further arguments (in '...').

_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 character string.

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

_D_e_t_a_i_l_s:

     If the value of 'EXPR' is an integer between 1 and 'nargs()-1'
     then the corresponding element 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 evaluated and returned if there is one,
     otherwise the next element is chosen, e.g., 'switch("cc", a=1,
     cc=, d=2)' evaluates to '2'.

     In the case of no match, if there's a further argument in 'switch'
     that one is returned, otherwise 'NULL'.

_W_a_r_n_i_n_g:

     Beware of partial matching: an alternative 'E = foo' will match
     the first argument 'EXPR' unless that is named. See the examples
     for good practice in naming the first argument.

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

_E_x_a_m_p_l_e_s:

     require(stats)
     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","bb")
     for(ch in ccc)
         cat(ch,":",switch(EXPR = ch, a=1,     b=2:3), "\n")
     for(ch in ccc)
         cat(ch,":",switch(EXPR = ch, a=, A=1, b=2:3, "Otherwise: last"),"\n")

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

