File: formatR.html

package info (click to toggle)
r-cran-formatr 1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 232 kB
  • sloc: sh: 10; makefile: 4
file content (389 lines) | stat: -rw-r--r-- 16,216 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>An Introduction to formatR</title>
<link rel="stylesheet" media="all" href="https://jashkenas.github.io/docco/resources/linear/public/stylesheets/normalize.css" />
<link rel="stylesheet" media="all" href="https://jashkenas.github.io/docco/resources/linear/docco.css" />
<link href='https://yihui.github.io/media/css/docco-linear.css' rel='stylesheet' type='text/css'>
<style type="text/css">
img{display:block;margin:auto;}
.container{width:auto;max-width:920px;}
.page{width:auto;max-width:800px;}
.page pre{width:100%;max-width:768px;}
pre, code{font-size:90%;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.3/languages/r.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="https://yihui.github.io/media/js/center-images.js"></script>


</head>

<body>
  <div class="container">
    <div class="page">
<!--
%\VignetteEngine{knitr::docco_linear}
%\VignetteIndexEntry{An Introduction to formatR}
-->

<script type="text/javascript">
if (location.protocol === 'https:' && location.href.match('yihui.name') === null)
  location.href = 'http://yihui.name/formatR';
</script>

<h1>An Introduction to formatR</h1>

<h2>1. Installation</h2>

<p>You can install <strong>formatR</strong> from <a href="https://cran.r-project.org/package=formatR">CRAN</a>, or <a href="http://yihui.name/xran">XRAN</a> if you want to test the latest development version:</p>

<pre><code class="r">install.packages(&quot;formatR&quot;, repos = &quot;http://cran.rstudio.com&quot;)
#&#39; to install the development version, run
#&#39; install.packages(&#39;formatR&#39;, repos = &#39;http://yihui.name/xran&#39;)
</code></pre>

<p>Or check out the <a href="https://github.com/yihui/formatR">Github repository</a> and install from source if you know what this means. This page is always based on the development version.</p>

<pre><code class="r">library(formatR)
sessionInfo()
</code></pre>

<pre><code>## R version 3.2.5 (2016-04-14)
## Platform: x86_64-apple-darwin15.4.0 (64-bit)
## Running under: OS X 10.11.4 (El Capitan)
## 
## locale:
## [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] formatR_1.4
## 
## loaded via a namespace (and not attached):
## [1] magrittr_1.5       tools_3.2.5        stringi_1.0-1     
## [4] knitr_1.13         stringr_1.0.0.9000 evaluate_0.9
</code></pre>

<h2>2. Reformat R code</h2>

<p>The <a href="https://cran.r-project.org/package=formatR"><strong>formatR</strong></a> package was designed to reformat <a href="https://www.r-project.org">R</a> code to improve readability; the main workhorse is the function <code>tidy_source()</code>. Features include:</p>

<ul>
<li>long lines of code and comments are reorganized into appropriately shorter ones</li>
<li>spaces and indent are added where necessary</li>
<li>comments are preserved in most cases</li>
<li>the number of spaces to indent the code (i.e. tab width) can be specified (default is 4)</li>
<li>an <code>else</code> statement in a separate line without the leading <code>}</code> will be moved one line back</li>
<li><code>=</code> as an assignment operator can be replaced with <code>&lt;-</code></li>
<li>the left brace <code>{</code> can be moved to a new line</li>
</ul>

<p>Below is an example of what <code>tidy_source()</code> can do. The source code is:</p>

<pre><code class="r">## comments are retained;
# a comment block will be reflowed if it contains long comments;
#&#39; roxygen comments will not be wrapped in any case
1+1

if(TRUE){
x=1  # inline comments
}else{
x=2;print(&#39;Oh no... ask the right bracket to go away!&#39;)}
1*3 # one space before this comment will become two!
2+2+2    # only &#39;single quotes&#39; are allowed in comments

lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100)))  ### a linear model
1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1  ## comments after a long line
## here is a long long long long long long long long long long long long long comment which will be wrapped
</code></pre>

<p>We can copy the above code to clipboard, and type <code>tidy_source(width.cutoff = 70)</code> to get:</p>

<pre><code class="r">## comments are retained; a comment block will be reflowed if it
## contains long comments;
#&#39; roxygen comments will not be wrapped in any case
1 + 1

if (TRUE) {
    x = 1  # inline comments
} else {
    x = 2
    print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
1 * 3  # one space before this comment will become two!
2 + 2 + 2  # only &#39;single quotes&#39; are allowed in comments

lm(y ~ x1 + x2, data = data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100)))  ### a linear model
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 
    1 + 1 + 1 + 1 + 1  ## comments after a long line
## here is a long long long long long long long long long long long long
## long comment which will be wrapped
</code></pre>

<p>Two applications of <code>tidy_source()</code>:</p>

<ul>
<li><code>tidy_dir()</code> can reformat all R scripts under a directory</li>
<li><p><code>usage()</code> can reformat the usage of a function, e.g. compare <code>usage()</code> with the default output of <code>args()</code>:</p>

<pre><code class="r">library(formatR)
usage(glm, width = 70)  # can set arbitrary width here
## glm(formula, family = gaussian, data, weights, subset, na.action, start = NULL, 
##     etastart, mustart, offset, control = list(...), model = TRUE, method = &quot;glm.fit&quot;, 
##     x = FALSE, y = TRUE, contrasts = NULL, ...)
args(glm)
## function (formula, family = gaussian, data, weights, subset, 
##     na.action, start = NULL, etastart, mustart, offset, control = list(...), 
##     model = TRUE, method = &quot;glm.fit&quot;, x = FALSE, y = TRUE, contrasts = NULL, 
##     ...) 
## NULL
</code></pre></li>
</ul>

<h2>3. The Graphical User Interface</h2>

<p>If the <strong>shiny</strong> packages has been installed, the function <code>tidy_app()</code> can launch a Shiny app to reformat R code like this (<a href="https://yihui.shinyapps.io/formatR/">live demo</a>):</p>

<pre><code class="r">formatR::tidy_app()
</code></pre>

<p><a href="https://yihui.shinyapps.io/formatR/"><img src="http://i.imgur.com/lUgtEAb.png" alt="R source code before tidying"/></a></p>

<p>After hitting the <code>Tidy</code> button:</p>

<p><a href="https://yihui.shinyapps.io/formatR/"><img src="http://i.imgur.com/TBZm0B8.png" alt="R source code after tidying"/></a></p>

<h2>4. Evaluate the code and mask output in comments</h2>

<p>It is often a pain when trying to copy R code from other people&#39;s code which has been run in R and the prompt characters (usually <code>&gt;</code>) are attached in the beginning of code, because we have to remove all the prompts <code>&gt;</code> and <code>+</code> manually before we are able to run the code. However, it will be convenient for the reader to understand the code if the output of the code can be attached. This motivates the function <code>tidy.eval()</code>, which uses <code>tidy_source()</code> to reformat the source code, evaluates the code in chunks, and attaches the output of each chunk as comments which will not actually break the original source code. Here is an example:</p>

<pre><code class="r">set.seed(123)
tidy_eval(text = c(&quot;a&lt;-1+1;a  # print the value&quot;, &quot;matrix(rnorm(10),5)&quot;))
</code></pre>

<pre><code>a &lt;- 1 + 1
a  # print the value
## [1] 2

matrix(rnorm(10), 5)
##             [,1]       [,2]
## [1,] -0.56047565  1.7150650
## [2,] -0.23017749  0.4609162
## [3,]  1.55870831 -1.2650612
## [4,]  0.07050839 -0.6868529
## [5,]  0.12928774 -0.4456620
</code></pre>

<p>The default source of the code is from clipboard like <code>tidy_source()</code>, so we can copy our code to clipboard, and simply run this in R:</p>

<pre><code class="r">library(formatR)
tidy_eval()  # without specifying any arguments, it reads code from clipboard
</code></pre>

<h2>5. Showcase</h2>

<p>We continue the example code in Section 2, using different arguments in <code>tidy_source()</code> such as <code>arrow</code>, <code>blank</code>, <code>indent</code>, <code>brace.newline</code> and <code>comment</code>, etc.</p>

<h3>Replace <code>=</code> with <code>&lt;-</code></h3>

<pre><code class="r">if (TRUE) {
    x &lt;- 1  # inline comments
} else {
    x &lt;- 2
    print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
</code></pre>

<h3>Discard blank lines</h3>

<p>Note the 5th line (an empty line) was discarded:</p>

<pre><code class="r">## comments are retained; a comment block will be reflowed if it contains
## long comments;
#&#39; roxygen comments will not be wrapped in any case
1 + 1
if (TRUE) {
    x = 1  # inline comments
} else {
    x = 2
    print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
1 * 3  # one space before this comment will become two!
</code></pre>

<h3>Reindent code (2 spaces instead of 4)</h3>

<pre><code class="r">if (TRUE) {
  x = 1  # inline comments
} else {
  x = 2
  print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
</code></pre>

<h3>Move left braces <code>{</code> to new lines</h3>

<pre><code class="r">if (TRUE)
{
    x = 1  # inline comments
} else
{
    x = 2
    print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
</code></pre>

<h3>Discard comments</h3>

<pre><code class="r">1 + 1
if (TRUE) {
    x = 1
} else {
    x = 2
    print(&quot;Oh no... ask the right bracket to go away!&quot;)
}
1 * 3
2 + 2 + 2
lm(y ~ x1 + x2, data = data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100)))
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 
    1 + 1 + 1 + 1
</code></pre>

<h2>6. Further notes</h2>

<p>The tricks used in this packages are very dirty. There might be dangers in using the functions in <strong>formatR</strong>. Please read the next section carefully to know exactly how comments are preserved. The best strategy to avoid failure is to put comments in complete lines or after <em>complete</em> R expressions. Below are some known issues that <code>tidy_source()</code> may fail.</p>

<h3>In-line comments after an incomplete expression or ;</h3>

<pre><code class="r">1 + 2 + ## comments after an incomplete line
    3 + 4
x &lt;- ## this is not a complete expression
     5
x &lt;- 1; # you should not use ; here!
</code></pre>

<p>It is not a good idea to interrupt R code with comments and sometimes it can be confusing &ndash; comments should come after a complete R expression naturally; by the way, <code>tidy_source()</code> will move the comments after <code>{</code> to the next line, e.g.</p>

<pre><code class="r">if (TRUE) {## comments
}
</code></pre>

<p>will become</p>

<pre><code class="r">if (TRUE) {
    ## comments
}
</code></pre>

<h3>Inappropriate blank lines</h3>

<p>Blank lines are often used to separate complete chunks of R code, and arbitrary blank lines may cause failures in <code>tidy_source()</code> as well when the argument <code>blank = TRUE</code>, e.g.</p>

<pre><code class="r">if (TRUE)

{&#39;this is a BAD style of R programming!&#39;} else &#39;failure!&#39;
</code></pre>

<p>There should not be a blank line after the <code>if</code> statement. Of course <code>blank = FALSE</code> will not fail in this case.</p>

<h3><code>?</code> with comments</h3>

<p>We can use the question mark (<code>?</code>) to view the help page, but <strong>formatR</strong> package is unable to correctly format the code using <code>?</code> with comments, e.g.</p>

<pre><code class="r">?sd  # help on sd()
</code></pre>

<p>In this case, it is recommended to use the function <code>help()</code> instead of the short-hand version <code>?</code>.</p>

<h3><code>-&gt;</code> with comments</h3>

<p>We can also use the right arrow <code>-&gt;</code> for assignment, e.g. <code>1:10 -&gt; x</code>. I believe this flexibility is worthless, and it is amazing that a language has three assignment operators: <code>&lt;-</code>, <code>=</code> and <code>-&gt;</code> (whereas almost all other languages uses <code>=</code> for assignment). Bad news for <strong>formatR</strong> is that it is unable to format code using both <code>-&gt;</code> and comments in a line, e.g.</p>

<pre><code class="r">1:10 -&gt; x  # assignment with right arrow
</code></pre>

<p>I recommend you to use <code>&lt;-</code> or <code>=</code> consistently. What is more important is consistency. I always use <code>=</code> because it causes me no confusion (I do not believe it is ever possible for people to interpret <code>fun(a = 1)</code> as assigning <code>1</code> to a variable <code>a</code> instead of passing an argument value) and <code>&lt;-</code> is more dangerous because it works everywhere (you might have unconsciously created a new variable <code>a</code> in <code>fun(a &lt;- 1)</code>; see <a href="https://stat.ethz.ch/pipermail/r-devel/2011-December/062786.html">an example here</a>). The only disadvantage is that most R people use <code>&lt;-</code> so it may be difficult to collaborate with other people.</p>

<h2>7. How does <code>tidy_source()</code> actually work?</h2>

<p>The method to preserve comments is to protect them as strings in R expressions. For example, there is a single line of comments in the source code:</p>

<pre><code class="r">  # asdf
</code></pre>

<p>It will be first masked as</p>

<pre><code class="r">invisible(&quot;.IDENTIFIER1  # asdf.IDENTIFIER2&quot;)
</code></pre>

<p>which is a legal R expression, so <code>base::parse()</code> can deal with it and will no longer remove the disguised comments.  In the end the identifiers will be removed to restore the original comments, i.e. the strings <code>invisible(&quot;.IDENTIFIER1</code> and <code>.IDENTIFIER2&quot;)</code> are replaced with empty strings.</p>

<p>Inline comments are handled differently: two spaces will be added before the hash symbol <code>#</code>, e.g.</p>

<pre><code class="r">1+1#  comments
</code></pre>

<p>will become</p>

<pre><code class="r">1+1  #  comments
</code></pre>

<p>Inline comments are first disguised as a weird operation with its preceding R code, which is essentially meaningless but syntactically correct!  For example,</p>

<pre><code class="r">1+1 %InLiNe_IdEnTiFiEr% &quot;#  comments&quot;
</code></pre>

<p>then <code>base::parse()</code> will deal with this expression; again, the disguised comments will not be removed. In the end, inline comments will be freed as well (remove the operator <code>%InLiNe_IdEnTiFiEr%</code> and surrounding double quotes).</p>

<p>All these special treatments to comments are due to the fact that <code>base::parse()</code> and <code>base::deparse()</code> can tidy the R code at the price of dropping all the comments.</p>

<h2>8. Global options</h2>

<p>There are global options which can override some arguments in <code>tidy_source()</code>:</p>

<table><thead>
<tr>
<th>argument</th>
<th>global option</th>
<th>default</th>
</tr>
</thead><tbody>
<tr>
<td><code>comment</code></td>
<td><code>options(&#39;formatR.comment&#39;)</code></td>
<td><code>TRUE</code></td>
</tr>
<tr>
<td><code>blank</code></td>
<td><code>options(&#39;formatR.blank&#39;)</code></td>
<td><code>TRUE</code></td>
</tr>
<tr>
<td><code>arrow</code></td>
<td><code>options(&#39;formatR.arrow&#39;)</code></td>
<td><code>FALSE</code></td>
</tr>
<tr>
<td><code>indent</code></td>
<td><code>options(&#39;formatR.indent&#39;)</code></td>
<td><code>4</code></td>
</tr>
<tr>
<td><code>brace.newline</code></td>
<td><code>options(&#39;formatR.brace.newline&#39;)</code></td>
<td><code>FALSE</code></td>
</tr>
</tbody></table>

<p>Also note that single lines of long comments will be wrapped into shorter ones automatically, but roxygen comments will not be wrapped (i.e., comments that begin with <code>#&#39;</code>).</p>

      <div class="fleur">h</div>
    </div>
  </div>
</body>
</html>