Search notes:

R switch statement: Error in switch … EXPR must be a length 1 vector

english <- c('one', 'three', 'two', 'one', 'four', 'three', 'one');
Github repository about-r, path: /statements/switch/vector/english.R
Trying to use the switch statement causes Error in switch … EXPR must be a length 1 vector:
german <- switch(vec,
    'one'   = 'eins',
    'two'   = 'zwei',
    'three' = 'drei',
    'four'  = 'vier'
);
Github repository about-r, path: /statements/switch/vector/switch.R
A simple method to look up the german words might be to use an additional vector and the bracket operator:
translation <- c(
    'one'   = 'eins',
    'two'   = 'zwei',
    'three' = 'drei',
    'four'  = 'vier'
);

translation[english];
#
#        one  three    two    one   four  three    one 
#     "eins" "drei" "zwei" "eins" "vier" "drei" "eins" 
Github repository about-r, path: /statements/switch/vector/translation.R
The desired functionality might also be achieved with a cascaded ifelse:
german <- ifelse(english == 'one'  , 'eins',
          ifelse(english == 'two'  , 'zwei',
          ifelse(english == 'three', 'drei',
          ifelse(english == 'four' , 'vier',
                 '?' ))))
Github repository about-r, path: /statements/switch/vector/ifelse.R
Another possibility is to put the switch statement into a function and then to use sapply to call the function with each element of english:
en2gr <- function(en) {
  switch(en, 
    'one'   = 'eins',
    'two'   = 'zwei',
    'three' = 'drei',
    'four'  = 'vier'
  );
}

sapply(english, en2gr);
Github repository about-r, path: /statements/switch/vector/sapply.R
The function can also be vectorized with Vectorize(…):
en2gr_vec <- Vectorize(en2gr);

en2gr_vec(english);
Github repository about-r, path: /statements/switch/vector/Vectorize.R
Finally, the package broman has a special function for such a switch statement: switchv.

See also

switch(…)

Index