11.10 Reformat R source code

When you set the chunk option tidy = TRUE, the R source code will be reformatted by the tidy_source() function in the formatR package (Xie 2019a). The tidy_source() can reformat the code in several aspects, such as adding spaces around most operators, indenting the code properly, and replacing the assignment operator = with <-. The chunk option tidy.opts can be a list of arguments to be passed to formatR::tidy_source(), e.g.,

  1. ```{r, tidy=TRUE, tidy.opts=list(arrow=TRUE, indent=2)}
  2. # messy R code...
  3. 1+ 1
  4. x=1:10#some users prefer '<-' as the assignment operator
  5. if(TRUE){
  6. print('Hello world!') # indent by 2 spaces
  7. }
  8. ```

The output:

  1. # messy R code...
  2. 1 + 1
  3. x <- 1:10 #some users prefer '<-' as the assignment operator
  4. if (TRUE) {
  5. print("Hello world!") # indent by 2 spaces
  6. }

In Section 5.3, we mentioned how to control the width of text output. If you want to control the width of the source code, you may try the width.cutoff argument when tidy = TRUE, e.g.,

  1. ```{r, tidy=TRUE, tidy.opts=list(width.cutoff=50)}
  2. # a long expression
  3. 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+
  4. 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1
  5. ```

The output:

  1. # a long expression
  2. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
  3. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
  4. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
  5. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1

Please read the help page ?formatR::tidy_source to know the possible arguments, and also see https://yihui.org/formatR/ for examples and limitations of this function.

Alternatively, you may use the styler package (Müller and Walthert 2020) to reformat your R code if you set the chunk option tidy = 'styler'. The R code will be formatted with the function styler::style_text(). The styler package has richer features than formatR. For example, it can align function arguments and works with the pipe operator %>%. The chunk option tidy.opts can also be used to pass additional arguments to styler::style_text(), e.g.,

  1. ```{r, tidy='styler', tidy.opts=list(strict=FALSE)}
  2. # align the assignment operators
  3. a <- 1#one variable
  4. abc <- 2#another variable
  5. ```

By default, tidy = FALSE and your R code will not be reformatted.

References

Müller, Kirill, and Lorenz Walthert. 2020. Styler: Non-Invasive Pretty Printing of r Code. https://github.com/r-lib/styler.

———. 2019a. formatR: Format r Code Automatically. https://github.com/yihui/formatR.