[R] Google's R Style Guide

Philippe Grosjean phgrosjean at sciviews.org
Sat Aug 29 18:12:30 CEST 2009


Max Kuhn wrote:
> Perhaps this is obvious, but Ive never understood why this is the
> general convention:
> 
>> An opening curly brace should never go on its own line;
> 
> I tend to do this:
> 
> f <- function()
> {
>   if (TRUE)
>     {
>       cat("TRUE!!\n")
>     } else {
>       cat("FALSE!!\n")
>     }
> }
> 
> (I don't usually put one-liners in if/else blocks; here I would have
> used ifelse)
> 
> I haven't seen many others format code in this way. Is there an
> objective reason for this (such as the rule for the trailing "}") or
> is this just aesthetics?

I think the problem is not much putting the opening brace after 
function(), or after if (...), like you do. The problem is putting the 
else at a new line like in:

if (TRUE) {
     cat("TRUE!!\n")
}
else
{
     cat("FALSE!!\n")
}

When you source this code, the first part until the first closing brace 
is considered complete by the R parser, and then, 'else' is considered 
as the begining of a new command, which is a syntax error:

 > if (TRUE) {
+     cat("TRUE!!\n")
+ }
TRUE!!
 > else
Error: syntax error
 > {
+     cat("FALSE!!\n")
+ }
FALSE!!

If you put the same code in a function, you got the expected behaviour:

 > f <- function () {
+     if (TRUE) {
+         cat("TRUE!!\n")
+     }
+     else
+     {
+         cat("FALSE!!\n")
+     }
+ }
 > f()  # No syntax error!
TRUE!!

Thus, this is technical reason for NOT putting else on another line.
For the rest, I share Hadley's feeling that you consumes "too much 
lines" and I tend to prefer the "regular" R syntax you got when you 
source your code.
Best,

Philippe


> Thanks,
> 
> Max
> 
> ______________________________________________
> 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