98

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.

Community
  • 1
  • 1
midas
  • 1,758
  • 2
  • 20
  • 20

6 Answers6

87

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.

user5249203
  • 4,436
  • 1
  • 19
  • 45
72

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

If on a Mac, use instead of CTRL.

butterflyeffect
  • 85
  • 1
  • 12
lu5er
  • 3,229
  • 2
  • 29
  • 50
35

Go to the Code menu and select

Reindent Lines

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

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
csgillespie
  • 59,189
  • 14
  • 150
  • 185
32

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. As of version 1.2.0, this also holds for the Addin.

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.

Lorenz Walthert
  • 4,414
  • 1
  • 18
  • 24
16

Use the formatR library (see documentation):

install.packages("formatR")
    
library("formatR")
    
tidy_eval("filename.R")
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Ashish
  • 441
  • 1
  • 5
  • 11
  • 1
    `{formatR}` compared to `{styler}` is faster but cannot parse all code, sometimes drops comments, handles `%>%` and `!!(!)` unexpectedly and a few other things, summarised here: https://github.com/r-lib/styler/issues/558#issuecomment-542883365 – Lorenz Walthert Jan 02 '21 at 19:32
5

To add to the great answers that were already given: You can use the styler package in combination with the shrtcts package to enable Format on Save which is still not officially supported by RStudio.

  1. Use the command shrtcts::edit_shortcuts() in the RStudio Console to open the file where you define your custom shortcuts.

  2. Paste the following code inside that file (set your preferred keybinding in the @shortcut line).

    #' Format on Save
    #'
    #' @description
    #'   Format Document with styler Package and Save Document.
    #' @interactive
    #' @shortcut Cmd+S
    function() {
      # format only .R and .Rmd files, but save all file types
      file_type <- tools::file_ext(rstudioapi::getActiveDocumentContext()$path)
    
      if (file_type %in% c("R", "Rmd", "qmd")) {
        styler:::style_active_file() |>
          capture.output() |>
          invisible()
      }
    
      rstudioapi::documentSave() |>
        capture.output() |>
        invisible()
    }
    

    This solution uses the native pipe |> and thus requires R 4.1. You can of course just define separate variables in each line or use the magrittr pipe if you use earlier versions of R.

  3. Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.

With this configuration pressing Cmd+S formats the active .R or .Rmd document with the styler package and saves the formatted version afterwards. Files of all other types are saved without formatting, but you could easily extend the code above with a package that formats e.g. .md or .py files as well.

There exist cases where this approach code does not have the desired effect, for instance it does not work for new Untitled files or when your current R session is busy.

RoyalTS
  • 9,545
  • 12
  • 60
  • 101
Joel Beck
  • 318
  • 2
  • 6
  • The function you wrote is very neat. I first overlooked that it is `cmd+S` and not `Ctrl+S` and took me a while to figure why it would not work. Thanks alot – Björn May 02 '22 at 18:32
  • This is great! One of my most missed features in RStudio. – Grassie Mar 10 '23 at 17:28
  • Awesome! Just what I've been wanting. The only issue I can see is if there is a syntax error in the R code, the styling wont work and the file won't save. – cameron.bracken Jun 14 '23 at 16:30