Auto-format R code in RStudio

midas picture midas · Mar 29, 2013 · Viewed 59.1k times · Source

Is there any possibilities for auto-formatting code in RStudio?

I found this, but it is not connected with RStudio.

Also it is desirable that it be customizable formatting.

Answer

user5249203 picture user5249203 · Jan 18, 2016

update: June-22-2018

Thank you @Lorenz@kirill@yuhi for styler package. I have used it for a while. The simplest after installation of the package is to just use

scroll to Addin --> style active file

Customization options via interface would give some control on styling we prefer.

Rstudio can now format code to look neat. Select the lines of interest and then navigate to Code >> Reformat code or use the keyboard shortcut Ctrl + Shift + A.

update: This is a good way to re-structure the code, but it breaks at , for the elements of a vector. For few this is OK, but with many elements passed to a vector, it is overkill:

x <- c(
  "p.G12C",
  "p.F121S",
  "p.P124S",
  "p.P124L",
  "p.E13D",
  "p.E203K",
  "p.Q209P",
  "p.Q209P",
  "p.Q209L"
)

Update: R-Studio Version 0.99.893

There is a new feature that has been added by R-studio Addins. Part of this addins, now you can add @yuhi formatR as an Addin. This is more tidy and cleaner way to structure code than the built-in code >> Refromat code. However, the drawback with the Addin Reformat R Code it throws an error for Rshiny codes.