Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-format R code in RStudio

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.

like image 201
midas Avatar asked Mar 29 '13 12:03

midas


People also ask

How do you fix an indent in R?

Reformat R scriptsCtrl + I – Fixes line indentations. Ctrl + Shift + A – Does a complete reformat of the selected part of a code.

How do you create a section in R?

Insert Section — Ctrl+Shift+R (Cmd+Shift+R on the Mac)


1 Answers

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.

or just run the style directory command to style all the files in the directory.

styler::style_dir() 

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.

like image 107
user5249203 Avatar answered Sep 21 '22 13:09

user5249203