Search code examples
rformateditor

How to format R code from the command line?


I am new to R and am trying to set up a minimal R development environment on my machine. I want to set up an auto-formatter for R code which formats my code upon save (Like prettier, ruff or rustfmt).

After looking into the problem it seems like styler and formatR packages seem to do what I want, but these offer API's to format files from R code using functions. What I want is a command line tool (like ruff or rustfmt) with which I can set up a hook to format my files on save from my editor (Neovim and Helix). However upon going through the documentation of the libraries, neither seem to provide a command line utility.

effectively what I want is to run the following from a terminal:

toolname Rfile.R 

and get the formatted version of RFile.R.

Does anyone have any suggestions on how I can go about this? Any help is greatly appreciated.


Solution

  • Create a file rformat and make it executable.

    #!/bin/sh
    Rscript -e "styler::style_file('$1')"
    

    give it execute permission:

    chmod +x rformat
    

    format files with it:

    ./rformat my_script.R
    

    Or use styleR -> install.packages("styler") Save the following script as format.R:

    #!/usr/bin/env Rscript
    
    args <- commandArgs(trailingOnly = TRUE)
    
    if (length(args) != 1) {
      stop("Usage: format.R <file>")
    }
    
    file_path <- args[1]
    
    if (!file.exists(file_path)) {
      stop("File does not exist: ", file_path)
    }
    library(styler)    
    style_file(file_path)
    

    make it executable again

    chmod +x format.R
    

    and run

    ./format.R path/to/your/file.R
    

    To integrate this with Neovim, you can set up an autocommand to run the script whenever you save an R file. Add the following to your Neovim configuration init.vim:

    autocmd BufWritePost *.R silent !./path/to/format.R %
    

    It also depends on your IDE. The easiest for me is to use RStudio, mark everything (Ctrl + A) and autoformat everything (Ctrl + Shift + A). It takes 2 seconds and is super easy. You could maybe even mingle with your .rProfile file and change the .last function to autoformat all code in the directory.