[R] looking for alternative of 'if-else'
ctu at bigred.unl.edu
ctu at bigred.unl.edu
Sun Jul 6 12:08:15 CEST 2008
Why don't you try "switch" Let me assume that you want to calculate
a=3 and b =5 by using one of "MEAN", "SUM","MIN", and "MAX functions.
Then you could write your code: (If you want to calculate "MEAN")
> example<-function(fun=c("MEAN", "SUM", "MIN", "MAX")){
+ fun<-match.arg(fun);a=3;b=5
+ switch( fun,
+ MEAN=(a+b)/2,
+ SUM=a+b,
+ MIN=min(a,b),
+ MAX=max(a,b))
+ }
> example("MEAN")
[1] 4
>
Hope this is helpful,
Chunhao Tu
Quoting Arun Kumar Saha <arun.kumar.saha at gmail.com>:
> There is "if-else" loop if I have to choose 1 item from a 2-item list.
> However if I have a list of 4 items (let say) then how i can choose a single
> item without employing 'if-else' loop? I mean in VBA I can use
> "select-case", is there any equivalent in R as well?
>
> Regards,
>
> [[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