[R] Switch and integer

Dieter Menne dieter.menne at menne-biomed.de
Mon Dec 11 10:47:01 CET 2006


Knut Krueger <Knut-krueger <at> einthal.de> writes:

> 
> Switch is working with character , with integer, but not in the third 
> example
... 
> # -------- not working
test = c(3,9,3,9,3,9,8,9,8,9,8,9,3,9,3,9,5,9,3,9,1,2,7,9,3,9,1,1,
2,2,3,9,2,1,2,5, 9,8,9,1,2)
> count1 <- 0
> for (i in 1:length(test))
>   switch (EXPR=test[i],
>       4 =     count1 <- count1 +1,
>       5 =     count1 <- count1 +1,
>       6 =     count1 <- count1 +1,
>       7 =     count1 <- count1 +1,
>       8 =     count1 <- count1 +1
>       )
>   count1
> 

switch has a different behavior when an integer is use, which is a bit hidden 
in the term "corresponding". 

"If the value of EXPR is an integer between 1 and nargs()-1 then the
corresponding element of ... is evaluated and the result returned."

So something like the example below might come close to what you want. 
In each case you have to add the default last item to avoid a NULL.

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

Dieter

test =c(4,5,8,1,13)
count1 <- 0
for (i in 1:length(test)) {
  count1 <- switch (EXPR=as.character(test[i]),
      "4" =     count1 +1,
      "5" =     count1 +1,
      "6" =     count1 +1,
      "7" =     count1 +1,
      "8" =     count1 +1,
      count1
      )
}
count1




More information about the R-help mailing list