[R] else if statement error

Martin Maechler maechler at stat.math.ethz.ch
Mon Oct 5 11:38:22 CEST 2009


>>>>> "DW" == David Winsemius <dwinsemius at comcast.net>
>>>>>     on Sat, 3 Oct 2009 12:56:51 -0400 writes:

    DW> On Oct 3, 2009, at 11:54 AM, Chen Gu wrote:

    >> Hello,
    >> 
    >> I am doing a simple if else statement in R. But it always comes out  
    >> error
    >> such as 'unexpected error'
    >> There are two variables. ini and b. when ini=1, a=3; when ini>1 and  
    b> 2,
    >> a=5; all other situations, a=6. I don't know where it is wrong.
    >> Here is my code
    >> 
    >> ini=3
    >> b=4
    DW> Your basic problem is that you are confusing if and else which are  
    DW> program control functions with ifelse which is designed for assignment  
    DW> purposes;

David, not quite:  in R, "everything"(*) is a function,
and in the example we have here 
(and innumerous similar examples)   ifelse(.) is not efficient
to use:
    >> ini=3
    >> b=4
    >> a <-   ifelse( ini==1, 3, ifelse( ini>1 & b>2 , 5, 6))
    >> 
    >> a
     > [1] 5

More efficient -- and also nicer in my eyes ---
is
	a <-  if(ini == 1) 3 else if(ini > 1 && b > 2) 5  else  6

As I say on many occasions:  
   ifelse() is useful and nice, but it is used in many more
   places than it should.... {BTW, not only because of examples like the above}.

Martin Maechler, ETH Zurich

----
(*) "almost"


    >> if (ini==1) {
    >> a=3
    >> }
    >> else if (ini>1 and b>2 ) {
    DW> The error is probably being thrown because "and" is not a valid  
    DW> conjunction operator in R.
    >> 1 and 1
    DW> Error: syntax error
    >> 1 & 1
    DW> [1] TRUE


    >> a=5
    >> }
    >> else {a=6}
    >> 
    >> e.

    DW> David Winsemius, MD
    DW> Heritage Laboratories
    DW> West Hartford, CT

    DW> ______________________________________________
    DW> R-help at r-project.org mailing list
    DW> https://stat.ethz.ch/mailman/listinfo/r-help
    DW> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
    DW> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list