Skip to content
Prev 105910 / 398506 Next

Switch and integer

Knut Krueger <Knut-krueger <at> einthal.de> writes:
...
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)
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