[R] R parser for If-else

Martin Maechler maechler at stat.math.ethz.ch
Wed Feb 25 09:03:15 CET 2009


>>>>> "D" == Dani  <danicyber at gmail.com>
>>>>>     on Tue, 24 Feb 2009 14:09:36 -0800 writes:

    D> Hi list,
    D> I don't know if somebody has spent a lot of time debugging strange
    D> problems with if else positioning - the parser seems to recognize only
    D> the syntax bellow - this is the only way of making these pieces of
    D> code to work.

    D> As far as i'm concerned, no examples were available (it would be so
    D> awesome to have them in the introductory manual!)

    D> #Try to change the placement of the keywords and you are dead! 
["dead"?] 

Oh dear... 
Note this has nothing to do with   if( ) .. else ..
but indeed with how things are parsed.

I think this is FAQ (or should become one):

?if [the help page you really should read before spending too
     much time or even post to R-help]  
has the following section

 >      Note that it is a common mistake to forget to put braces ('{ .. }')
 >      around your statements, e.g., after 'if(..)' or 'for(....)'.
 >      In particular, you should not have a newline between '}' and 
 >      'else' to avoid a syntax error in entering a 'if ... else'
 >      construct at the keyboard or via 'source'. For that reason, one
 >      (somewhat extreme) attitude of defensive programming is to always
 >      use braces, e.g., for 'if' clauses.

Regards,
Martin Maechler, ETH Zurich


    D> Ex1:
    D> if (1==1){
    D>  print('if')
    D>  print('if again')
    D>  }else
    D>  print('else')

    D> Ex2:
    D> if (2==2) print('if') else print('else')

    D> Ex3:
    D> if (2==2){
    D>  print('if')
    D>  print('if again')
    D>  }else
    D>  {
    D>  print('else')
    D>  print('else2')
    D>  }

    D> Ex4:
    D> if (2==2){
    D>  print('if')
    D>  print('if again')
    D> }else print('else')



    D> cheers,
    D> -------------------------------------
    D> Daniela

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




More information about the R-help mailing list