switch (PR#2033)

Peter Dalgaard BSA p.dalgaard@biostat.ku.dk
18 Sep 2002 00:19:36 +0200


rwehrens@sci.kun.nl writes:

> Consider these two functions:
> switchme <- function(type, ...) {
>   switch(type,
>          E = max(...),
>          V = length(...),
>          EII = sum(...),
>          VII = prod(...),
>          -100)
> }
> switchme2 <- function(type, ...) {
>   switch(type,
>          V = length(...),
>          EII = sum(...),
>          VII = prod(...),
>          -100)
> }
> The bottom one does what I expect. The top one only gives one answer,
> independent 
> of the second argument.
> > switchme2("V", 1:4)
> [1] 4
> > switchme2("X", 1:4)
> [1] -100
> > switchme2("EII", 1:4)
> [1] 10
> > switchme("V", 1:4)
> [1] 24
> > switchme("X", 1:4)
> [1] 24
> > switchme("EII", 1:4)
> [1] 24
>  
> Is there something special about "E"?

Yes. It matches the EXPR arg to switch using partial matching, so the
case selector becomes max(1:4) == 4 and the fourth case is used to gie
prod(1:4) == 24. Not a bug, although perhaps a feature regretted by
the inventor...

The workaround (except for avoiding case labels E, EX, EXP) is 

switchme <- function(type, ...) {
  switch(EXPR=type,
         E = max(...),
         V = length(...),
         EII = sum(...),
         VII = prod(...),
         -100)
}


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._