## 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 . 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.,

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


The output:

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

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.,

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


The output:

# a long expression
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
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 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 preserve alignment and works with tidyverse syntax such as %>%, !! or {{. The chunk option tidy.opts can also be used to pass additional arguments to styler::style_text(), e.g.,

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


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

### References

Müller, Kirill, and Lorenz Walthert. 2022. Styler: Non-Invasive Pretty Printing of r Code.
———. 2022b. formatR: Format r Code Automatically. https://github.com/yihui/formatR.