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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1745540979, '18.117.250.210', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/R/statements/switch/Error-in-switch_EXPR-must-be-length-1-vector(97): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78