Auto-format R code in RStudio

本秂侑毒 提交于 2019-11-28 16:38:49

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.

csgillespie

Go to the Code menu and select

Reindent Lines

Under my OS, this has the shortcut Ctrl + I.

lU5er

First CTRL+A, then CTRL+SHIFT+A.

The package styler can format R code and you can access it via a RStudio Addin that allows formatting the active file, the highlighted code, the package and more. A distinguishing feature is its flexibility, as the transformation of code according to a style guide is done separately from specifying the style guide. This allows styling according to arbitrary style guide.

We've implemented the tidyverse style guide while allowing for quite some flexibility in styling. Also, the pipe, tidyeval syntax and more is handled properly. You can read an introduction in this blog post.

If you don't want to follow the tidyverse style guide, you can have a look at the vignette 'Customizing Styler' that describes how you can implement an arbitrary style guide. In this vignette, I show how you can implement a style guide consisting of one rule: Always break the line before {. Hope that helps.

Disclosure: I am the maintainer of styler.

Ashish
#use the library "formatR"

install.packages("formatR")

library(formatR)

# tidy_eval("file path")
tidy_eval("C:/Users/PC_name/Desktop/myfile.R")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!