为了开发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代码格式化,包括对齐、= 变 <- 等。

R包开发之代码格式化 - 图1

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 做了个图形界面。

R包开发之代码格式化 - 图2

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