[R] Switch and integer

David Barron mothsailor at googlemail.com
Mon Dec 11 10:42:28 CET 2006


>From the help entry for switch:

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, for integers you don't give names to the elements in ...  This should work:

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],
     NULL,
     NULL,
     NULL,
     count1 <- count1 +1,
     count1 <- count1 +1,
     count1 <- count1 +1,
     count1 <- count1 +1,
     count1 <- count1 +1,
     NULL
     )
 count1


On 11/12/06, Knut Krueger <Knut-krueger at einthal.de> wrote:
> I searched the help list and the manual, but I do not find my mistake.
> Switch is working with character , with integer, but not in the third
> example
>
> Regards Knut
>
>
> count1 <- 0
> 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],
>       "5" =     print(test[i]),
>       "6" =     print(test[i]),
>       "7" =     print(test[i]),
>       "8" =     print(test[i]),
>       "9" =     print(test[i])
>       )
>   count1
> #         example from helpfile
> for(i in c(-1:3,9))  print(switch(i, 1,2,3,4))
>
> # -------- 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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
=================================
David Barron
Said Business School
University of Oxford
Park End Street
Oxford OX1 1HP




More information about the R-help mailing list