[R] Odp: Help needed on "switch" function

From: Petr PIKAL <petr.pikal_at_precheza.cz>
Date: Wed, 09 Jun 2010 14:24:22 +0200

Hi

if you do not insist on switch you can use factor to get desired result

set.seed(666)
x<-sample(1:5,20, replace=T)
x
 [1] 4 1 5 2 2 4 5 3 1 2 4 1 1 1 2 5 1 5 3 3 factor(x, labels=letters[1:5])
 [1] d a e b b d e c a b d a a a b e a e c c Levels: a b c d e

r-help-bounces_at_r-project.org napsal dne 09.06.2010 12:36:26:

> Hi all, Here I am trying to implement the switch() function to choose
value of
> a variable depending on the value of an input variable :
>
> temp1 <- "1"
> temp1.name <- switch(temp1,
> 1 == "aa",
> 2 == "bb",
> 3 == "cc",
> 4 == "dd",
> 5 == "ee")
>
> Goal is if "temp1" equals to 1, then value of temp1.name would be "aa".
> However I am getting following answer :
>
> > temp1 <- "1"
> > temp1.name <- switch(temp1,
> + 1 == "aa",
> + 2 == "bb",
> + 3 == "cc",
> + 4 == "dd",
> + 5 == "ee")
> > temp1.name
> [1] FALSE
>
>
> Can anyone please point me where I am doing wrong?

Have you looked at help ?switch

Arguments
EXPR

an expression evaluating to a number or a character string.
                                          ^^^^^^^^^^^^^^^^^^^^^^ 



...
the list of alternatives. If it is intended that EXPR has a character-string value these will be named, perhaps except for one alternative to be used as a ‘default’ value.

So in your case

temp1 <- "1"

               temp1.name <- switch(temp1,
                                   "1" = "aa",
                                   "2" = "bb",
                                   "3" = "cc",
                                   "4" = "dd",
                                   "5" = "ee")


Basically switch compares your temp1 with all LHS alternatives, if it match it returns RHS. If it does not it will return NULL and in your case it returned probably value 1=="aa" which is FALSE.

Regards
Petr

>
> Thanks,
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org 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.



R-help_at_r-project.org 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. Received on Wed 09 Jun 2010 - 12:27:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 09 Jun 2010 - 12:40:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive