~mwinter4/maus/ckov_0_9_3

« back to all changes in this revision

Viewing changes to third_party/google-styleguide/google-r-style.html

  • Committer: tunnell
  • Date: 2010-09-30 13:56:05 UTC
  • Revision ID: tunnell@itchy-20100930135605-wxbkfgy75p0sndk3
add third party

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
 
2
 "http://www.w3.org/TR/REC-html4/strict.dtd">
 
3
<html>
 
4
  <head>
 
5
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 
6
    <link rel="stylesheet" type="text/css"
 
7
          href="http://www.corp.google.com/eng/docstyle.css">
 
8
    <title>Google's R Style Guide</title>
 
9
    <style type="text/css">
 
10
           ul.NoBullet {list-style-type: none}
 
11
    </style>
 
12
  </head>
 
13
 
 
14
  <body>
 
15
 
 
16
<!---------------------------------------------------------------------------->
 
17
 
 
18
  <h1>Google's R Style Guide</h1>
 
19
 
 
20
  <p>
 
21
    R is a high-level programming language used primarily for statistical
 
22
    computing and graphics.  The goal of the R Programming Style Guide
 
23
    is to make our R code easier to read, share, and verify. The rules
 
24
    below were designed in collaboration with the entire R user community
 
25
    at Google.
 
26
  </p>
 
27
 
 
28
<!---------------------------------------------------------------------------->
 
29
 
 
30
  <ul class="NoBullet">
 
31
    <h2><li>Summary: R Style Rules</li></h2>
 
32
    <ol>
 
33
      <li><a href=#filenames>File Names</a>: end in <code>.R</code></li>
 
34
      <li><a href=#identifiers>Identifiers</a>: <code>variable.name</code>,
 
35
        <code>FunctionName</code>, <code>kConstantName</code></li>
 
36
 
 
37
      <li><a href=#linelength>Line Length</a>: maximum 80 characters</li>
 
38
      <li><a href=#indentation>Indentation</a>: two spaces, no tabs</li>
 
39
      <li><a href=#spacing>Spacing</a></li>
 
40
      <li><a href=#curlybraces>Curly Braces</a>: first on same line, last on
 
41
        own line</li>
 
42
      <li><a href=#assignment>Assignment</a>: use <code>&lt;-</code>, not
 
43
        <code>=</code></li>
 
44
 
 
45
      <li><a href=#semicolons>Semicolons</a>: don't use them</li>
 
46
      <li><a href=#generallayout> General Layout and Ordering</a></li>
 
47
      <li><a href=#comments> Commenting Guidelines</a>: all comments begin
 
48
        with <code>#</code> followed by a space; inline comments need two
 
49
        spaces before the <code>#</code></li>
 
50
 
 
51
      <li><a href=#functiondefinition>Function Definitions and Calls</a></li>
 
52
      <li><a href=#functiondocumentation> Function Documentation</a></li>
 
53
      <li><a href=#examplefunction> Example Function</a></li>
 
54
      <li><a href=#todo> TODO Style</a>: <code>TODO(username)</code></li>
 
55
 
 
56
    </ol>
 
57
    <h2><li>Summary: R Language Rules</li></h2>
 
58
    <ol>
 
59
      <li><a href=#attach> <code>attach</code></a>: avoid using it</li>
 
60
      <li><a href=#functionlanguage> Functions</a>:
 
61
        errors should be raised using <code>stop()</code></li>
 
62
 
 
63
      <li><a href=#object> Objects and Methods</a>: avoid S4 objects and
 
64
        methods when possible; never mix S3 and S4 </li>
 
65
    </ol>
 
66
  </ul>
 
67
 
 
68
  <br>
 
69
  <ol>
 
70
<!---------------------------------------------------------------------------->
 
71
 
 
72
    <h3><li>Notation and Naming</li></h3>
 
73
 
 
74
      <ul class="NoBullet">
 
75
        <h4 id="filenames"><li>File Names</li></h4>
 
76
          <p>
 
77
            File names should end in <code>.R</code> and, of course, be
 
78
            meaningful.
 
79
            <br> GOOD: <code>predict_ad_revenue.R</code>
 
80
            <br> BAD: <code><span style="color:red">foo.R</span></code>
 
81
 
 
82
          </p>
 
83
        <h4 id="identifiers"><li>Identifiers</li></h4>
 
84
          <p>
 
85
            Don't use underscores ( <code>_</code> ) or hyphens
 
86
            ( <code>-</code> ) in identifiers.
 
87
            Identifiers should be named according to the following conventions.
 
88
            Variable names should have all lower case letters and words
 
89
            separated with dots (<code>.</code>);
 
90
            function names have initial capital letters and no dots
 
91
            (CapWords);
 
92
            constants are named like functions but with an initial
 
93
            <code>k</code>.
 
94
          </p>
 
95
 
 
96
          <ul>
 
97
            <li><code>variable.name </code>
 
98
              <br> GOOD: <code>avg.clicks</code>
 
99
              <br> BAD: <code><span style="color:red">avg_Clicks
 
100
                </span></code>, <code><span style="color:red">avgClicks
 
101
                </span></code>
 
102
 
 
103
            </li>
 
104
            <li><code>FunctionName </code>
 
105
              <br> GOOD: <code>CalculateAvgClicks</code>
 
106
              <br> BAD: <code><span style="color:red">calculate_avg_clicks
 
107
                </span></code>,
 
108
                <code><span style="color:red">calculateAvgClicks</span></code>
 
109
 
 
110
              <br> Make function names verbs.
 
111
              <br><em>Exception: When creating a classed object, the function
 
112
                name (constructor) and class should match  (e.g., lm).</em>
 
113
            <li><code>kConstantName </code></li>
 
114
          </ul>
 
115
      </ul>
 
116
 
 
117
<!---------------------------------------------------------------------------->
 
118
 
 
119
    <h3><li>Syntax</li></h3>
 
120
 
 
121
      <ul class="NoBullet">
 
122
        <h4 id="linelength"><li>Line Length</li></h4>
 
123
          <p>
 
124
            The maximum line length is 80 characters.
 
125
          </p>
 
126
        <h4 id="indentation"><li>Indentation</li></h4>
 
127
          <p>
 
128
            When indenting your code, use two spaces.  Never use tabs or mix
 
129
            tabs and spaces.
 
130
            <br><em>Exception: When a line break occurs inside parentheses,
 
131
              align the wrapped line with the first character inside the
 
132
              parenthesis.</em>
 
133
 
 
134
          <p>
 
135
        <h4 id="spacing"><li>Spacing</li></h4>
 
136
          <p>
 
137
            Place spaces around all binary operators (<code>=</code>,
 
138
            <code>+</code>, <code>-</code>, <code>&lt;-</code>, etc.).
 
139
            <br><em> Exception:  Spaces around <code>=</code>'s are
 
140
            optional when passing parameters in a function call.</em>
 
141
 
 
142
          </p>
 
143
          <p>
 
144
            Do not place a space before a comma, but always place one after a
 
145
            comma.
 
146
            <br><br> GOOD:<pre><code>tabPrior &lt;- table(df[df$daysFromOpt &lt; 0, &quot;campaignid&quot;])
 
147
total &lt;- sum(x[, 1])
 
148
total &lt;- sum(x[1, ])</code></pre>
 
149
 
 
150
          </p>
 
151
          <p>
 
152
            BAD:<pre><code><span style="color:red">tabPrior &lt;- table(df[df$daysFromOpt&lt;0, &quot;campaignid&quot;])  # Needs spaces around '<'
 
153
tabPrior &lt;- table(df[df$daysFromOpt &lt; 0,&quot;campaignid&quot;])  # Needs a space after the comma
 
154
tabPrior&lt;- table(df[df$daysFromOpt &lt; 0, &quot;campaignid&quot;])  # Needs a space before &lt;-
 
155
tabPrior<-table(df[df$daysFromOpt &lt; 0, &quot;campaignid&quot;])  # Needs spaces around &lt;-
 
156
total &lt;- sum(x[,1])  # Needs a space after the comma
 
157
total &lt;- sum(x[ ,1])  # Needs a space after the comma, not before</span></code></pre>
 
158
 
 
159
          </p>
 
160
          <p>
 
161
            Place a space before left parenthesis, except in a function call.
 
162
          </p>
 
163
          <p>
 
164
            GOOD:
 
165
            <br><code>if (debug)</code>
 
166
          </p>
 
167
          <p>
 
168
 
 
169
            BAD:
 
170
            <br><code><span style="color:red">if(debug)</span></code>
 
171
          </p>
 
172
          <p>
 
173
            Extra spacing (i.e., more than one space in a row) is okay if it
 
174
            improves alignment of equals signs or arrows (<code><-</code>).
 
175
          </p>
 
176
<pre><code>plot(x    = xCoord,
 
177
     y    = dataMat[, makeColName(metric, ptiles[1], &quot;roiOpt&quot;)],
 
178
     ylim = ylim,
 
179
     xlab = &quot;dates&quot;,
 
180
     ylab = metric,
 
181
     main = (paste(metric, &quot; for 3 samples &quot;, sep=&quot;&quot;)))
 
182
 
 
183
</pre></code>
 
184
          <p>
 
185
            Do not place spaces around code in parentheses or square brackets.
 
186
            <br><em> Exception:  Always place a space after a comma.</em>
 
187
          </p>
 
188
          <p>
 
189
            GOOD: <pre><code>if (debug)
 
190
x[1, ]</code></pre>
 
191
          </p>
 
192
 
 
193
          <p>
 
194
            BAD:<pre><code><span style="color:red">if ( debug )  # No spaces around debug
 
195
x[1,]  # Needs a space after the comma </span></code></pre>
 
196
          </p>
 
197
        <h4 id="curlybraces"><li>Curly Braces</li></h4>
 
198
          <p>
 
199
            An opening curly brace should never go on its own line; a closing
 
200
            curly brace should always go on its own line.  You may omit curly
 
201
            braces when a block consists of a single statement; however, you
 
202
            must <em>consistently</em> either use or not use curly braces for
 
203
            single statement blocks.
 
204
          </p>
 
205
 
 
206
          <code><pre>
 
207
if (is.null(ylim)) {
 
208
  ylim &lt;- c(0, 0.06)
 
209
}</pre></code>
 
210
          <p>
 
211
            xor (but not both)
 
212
          </p>
 
213
          <code><pre>
 
214
if (is.null(ylim))
 
215
  ylim &lt;- c(0, 0.06)</pre></code>
 
216
          <p>
 
217
 
 
218
            Always begin the body of a block on a new line.
 
219
          </p>
 
220
          <p>
 
221
            BAD:
 
222
            <br><code><span style="color:red"> if (is.null(ylim))
 
223
              ylim &lt;- c(0, 0.06)</span></code>
 
224
            <br><code><span style="color:red"> if (is.null(ylim))
 
225
              {ylim &lt;- c(0, 0.06)} </span></code>
 
226
          </p>
 
227
 
 
228
        <h4 id="assignment"><li>Assignment</li></h4>
 
229
          <p>
 
230
            Use <code>&lt;-</code>, not <code>=</code>, for assignment.
 
231
          </p>
 
232
          <p>
 
233
            GOOD:
 
234
            <br><code> x &lt;- 5 </code>
 
235
 
 
236
          </p>
 
237
          <p>
 
238
            BAD:
 
239
            <br><code><span style="color:red"> x = 5</span></code>
 
240
          </p>
 
241
        <h4 id="semicolons"><li>Semicolons</li></h4>
 
242
          <p>
 
243
            Do not terminate your lines with semicolons or use semicolons to
 
244
            put more than one command on the same line. (Semicolons are not
 
245
            necessary, and are omitted for consistency with other Google style
 
246
            guides.)
 
247
          </p>
 
248
 
 
249
      </ul>
 
250
 
 
251
<!---------------------------------------------------------------------------->
 
252
 
 
253
    <h3><li> Organization </li></h3>
 
254
      <ul class="NoBullet">
 
255
        <h4 id="generallayout"><li>General Layout and Ordering</li></h4>
 
256
          <p>
 
257
            If everyone uses the same general ordering, we'll be able to
 
258
            read and understand each other's scripts faster and more easily.
 
259
          </p>
 
260
 
 
261
          <ol>
 
262
            <li>Copyright statement comment
 
263
            <li>Author comment
 
264
            <li>File description comment, including purpose of
 
265
              program, inputs, and outputs
 
266
            <li><code>source()</code> and <code>library()</code> statements
 
267
            <li>Function definitions
 
268
            <li>Executed statements, if applicable (e.g.,
 
269
              <code> print</code>, <code>plot</code>)
 
270
          </ol>
 
271
 
 
272
          <p>
 
273
            Unit tests should go in a separate file named
 
274
            <code>originalfilename_unittest.R</code>.
 
275
          <p>
 
276
        <h4 id="comments"><li>Commenting Guidelines</li></h4>
 
277
          <p>
 
278
            Comment your code. Entire commented lines should begin with
 
279
            <code>#</code> and one space.
 
280
          </p>
 
281
 
 
282
          <p>
 
283
            Short comments can be placed after code preceded by two spaces,
 
284
            <code>#</code>, and then one space.
 
285
          </p>
 
286
<pre><code># Create histogram of frequency of campaigns by pct budget spent.
 
287
hist(df$pctSpent,
 
288
     breaks = &quot;scott&quot;,  # method for choosing number of buckets
 
289
     main   = &quot;Histogram: fraction budget spent by campaignid&quot;,
 
290
     xlab   = &quot;Fraction of budget spent&quot;,
 
291
     ylab   = &quot;Frequency (count of campaignids)&quot;)
 
292
</code></pre>
 
293
 
 
294
        <h4 id="functiondefinition"><li> Function Definitions and
 
295
          Calls</li></h4>
 
296
          <p>
 
297
            Function definitions should first   list arguments without default
 
298
            values, followed by those with default values.
 
299
          </p>
 
300
          <p>
 
301
            In both function definitions and function calls, multiple
 
302
            arguments per line are allowed; line breaks are only allowed
 
303
            between assignments.
 
304
            <br>GOOD:
 
305
<pre><code>PredictCTR &lt;- function(query, property, numDays,
 
306
                       showPlot = TRUE)
 
307
</code></pre>
 
308
 
 
309
           BAD:
 
310
<pre><code><span style="color:red">PredictCTR &lt;- function(query, property, numDays, showPlot =
 
311
                       TRUE)
 
312
</span></code></pre>
 
313
          <p> Ideally, unit tests should serve as sample function calls (for
 
314
            shared library routines).
 
315
        <h4 id="functiondocumentation"><li> Function Documentation </li></h4>
 
316
          <p> Functions should contain a comments section immediately below
 
317
            the function definition line. These comments should consist of a
 
318
            one-sentence description of the function; a list of the function's
 
319
            arguments, denoted by <code>Args:</code>, with a description of
 
320
            each (including the data type); and a description of the return
 
321
            value, denoted by <code>Returns:</code>. The comments should be
 
322
            descriptive enough that a caller can use the function without
 
323
            reading any of the function's code.
 
324
 
 
325
 
 
326
        <h4 id="examplefunction"><li> Example Function </li></h4><pre><code>
 
327
 
 
328
CalculateSampleCovariance &lt;- function(x, y, verbose = TRUE) {
 
329
  # Computes the sample covariance between two vectors.
 
330
  #
 
331
  # Args:
 
332
  #   x: One of two vectors whose sample covariance is to be calculated.
 
333
  #   y: The other vector. x and y must have the same length, greater than one,
 
334
  #      with no missing values.
 
335
  #   verbose: If TRUE, prints sample covariance; if not, not. Default is TRUE.
 
336
  #
 
337
  # Returns:
 
338
  #   The sample covariance between x and y.
 
339
  n &lt;- length(x)
 
340
  # Error handling
 
341
  if (n &lt;= 1 || n != length(y)) {
 
342
    stop(&quot;Arguments x and y have invalid lengths: &quot;,
 
343
         length(x), &quot; and &quot;, length(y), &quot;.&quot;)
 
344
  }
 
345
  if (TRUE %in% is.na(x) || TRUE %in% is.na(y)) {
 
346
    stop(&quot; Arguments x and y must not have missing values.&quot;)
 
347
  }
 
348
  covariance &lt;- var(x, y)
 
349
  if (verbose)
 
350
    cat(&quot;Covariance = &quot;, round(covariance, 4), &quot;.\n&quot;, sep = &quot;&quot;)
 
351
  return(covariance)
 
352
}
 
353
 
 
354
</code></pre>
 
355
 
 
356
        <h4 id="todo"><li> TODO Style </li></h4>
 
357
          <p> Use a consistent style for TODOs throughout your code.
 
358
          <br><CODE>TODO(username): Explicit description of action to
 
359
          be taken</CODE>
 
360
  </ul>
 
361
 
 
362
<!---------------------------------------------------------------------------->
 
363
 
 
364
      <h3><li> Language </li></h3>
 
365
 
 
366
       <ul class="NoBullet">
 
367
        <h4 id="attach"><li> Attach </li></h4>
 
368
        <p> The possibilities for creating errors when using
 
369
          <code>attach</code> are numerous. Avoid it.
 
370
        <h4 id="functionlanguage"><li>Functions </li></h4>
 
371
        <p> Errors should be raised using <code>stop()</code>.
 
372
        <h4 id="object"><li>Objects and Methods</li></h4>
 
373
 
 
374
          <p> The S language has two object systems, S3 and S4, both of which
 
375
          are available in R.  S3 methods are more interactive and flexible,
 
376
          whereas S4 methods are more formal and rigorous. (For an illustration
 
377
          of the two systems, see Thomas Lumley's
 
378
          "Programmer's Niche: A Simple
 
379
          Class, in S3 and S4" in R News 4/1, 2004, pgs. 33 - 36:
 
380
          <a href="http://cran.r-project.org/doc/Rnews/Rnews_2004-1.pdf">
 
381
          http://cran.r-project.org/doc/Rnews/Rnews_2004-1.pdf</a>.)
 
382
          <p>Use S3 objects and methods unless there is a strong reason to use
 
383
            S4 objects or methods. A primary justification for an S4 object
 
384
            would be to use objects directly in C++ code. A primary
 
385
            justification for an S4 generic/method would be to dispatch on two
 
386
            arguments.
 
387
          <p>Avoid mixing S3 and S4: S4 methods ignore S3 inheritance and
 
388
            vice-versa.
 
389
        </ul>
 
390
 
 
391
 
 
392
<!---------------------------------------------------------------------------->
 
393
     <h3><li> Exceptions </li></h3>
 
394
 
 
395
     The coding conventions described above should be followed, unless
 
396
     there is good reason to do otherwise.  Exceptions include
 
397
     legacy code and modifying third-party code.
 
398
 
 
399
<!---------------------------------------------------------------------------->
 
400
     <h3><li> Parting Words </li></h3>
 
401
 
 
402
     Use common sense and BE CONSISTENT.
 
403
     <p>
 
404
     If you are editing code, take a few minutes to look at the code around
 
405
     you and determine its style. If others use spaces around their
 
406
     <code>if </code>
 
407
     clauses, you should, too. If their comments have little boxes of stars
 
408
     around them, make your comments have little boxes of stars around them,
 
409
     too.
 
410
     <p>
 
411
 
 
412
     The point of having style guidelines is to have a common vocabulary of
 
413
     coding so people can concentrate on <em>what</em> you are saying,
 
414
     rather than on <em>how</em> you are saying it. We present global style
 
415
     rules here so people
 
416
     know the vocabulary. But local style is also important. If code you add
 
417
     to a file looks drastically different from the existing code around it,
 
418
     the discontinuity will throw readers out of their rhythm when they go to
 
419
     read it. Try to avoid this.
 
420
 
 
421
     OK, enough writing about writing code; the code itself is much more
 
422
     interesting. Have fun!
 
423
 
 
424
<!---------------------------------------------------------------------------->
 
425
     <h3><li> References </li></h3>
 
426
 
 
427
     <a href="http://www.maths.lth.se/help/R/RCC/">
 
428
     http://www.maths.lth.se/help/R/RCC/</a> - R Coding Conventions
 
429
     <br>
 
430
     <a href="http://ess.r-project.org/">http://ess.r-project.org/</a> - For
 
431
     emacs users. This runs R in your emacs and has an emacs mode.
 
432
 
 
433
  </ol>
 
434
 
 
435
<!---------------------------------------------------------------------------->
 
436
 
 
437
 
 
438
 
 
439
</html>