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

Petr PIKAL petr.pikal at precheza.cz
Wed Jun 9 14:24:22 CEST 2010


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.



More information about the R-help mailing list