为了开发R包,写出漂亮、规范的R代码,需要一些代码检查、格式化的工具。
1. styler
styler allows you to format .R files, packages or entire R source trees according to a style guide. The following functions can be used for styling:
- style_text() to style a character vector.
- style_file() to style a single .R file.
- style_dir() to style all .R files in a directory.
- style_pkg() to style the source files of an R package.
- styler_addins (RStudio Addins) to style either selected code or the active file.
这个包还是一个Rstudio的插件(Addins),直接点击二级菜单里的 Styler选项就能对R代码格式化,包括对齐、= 变 <- 等。
2. formatR
The formatR package was designed to reformat R code to improve readability; the main workhorse is the function tidy_source(). Features include:
- long lines of code and comments are reorganized into appropriately shorter ones
- spaces and indent are added where necessary
- comments are preserved in most cases
- the number of spaces to indent the code (i.e. tab width) can be specified (default is 4)
- an else statement in a separate line without the leading } will be moved one line back
- = as an assignment operator can be replaced with <-
- the left brace { can be moved to a new line
这是谢益辉老大的包( https://yihui.name/formatR/),竟然还用 shiny 做了个图形界面。
3. lintr
lintr
is an R package offering static code analysis for R. It checks adherence to a given style, syntax errors and possible semantic issues, see the animation below. In this README find out
- what linters i.e. checks are supported;
- how to configure the project to e.g. tweak checks and ignore files;
- how to setup
lintr
for on-the-fly checking in different editors; - how to use
lintr
in combination with continuous integration;
这个包是静态的检查,不能像上面两个包对不规范的地方进行更改,但是可以检查出更多的错误。而且此工具除了支持Rstudio,还支持多个代码编辑器,例如Emacs、Sublime Text 3、Vim、Atom,牛逼坏了。更为详细内容查看 https://github.com/jimhester/lintr