Last updated: 2026-02-06
Token-based R code formatter following R Core style conventions.
Installation
1remotes::install_github("cornball-ai/rformat")
Usage
1library(rformat)
2
3# Format a code string
4rformat("x<-1+2")
5#> x <- 1 + 2
6
7# Format a file
8rformat_file("R/my_script.R")
9
10# Format all R files in a directory
11rformat_dir("R/")
Options
1# Default: 4-space indentation, paren alignment
2rformat(code)
3
4# Custom indentation (2 spaces)
5rformat(code, indent = 2L)
6
7# Tab indentation
8rformat(code, indent = "\t")
9
10# Fixed 8-space continuation (instead of paren alignment)
11rformat(code, wrap = "fixed")
12
13# Expand inline if-else to multi-line
14rformat(code, expand_if = TRUE)
Style
Based on analysis of actual R Core source code (see vignette("r-core-style")).
Spacing
- Spaces around binary operators:
x <- 1 + 2 - Space after
function:function (x, y) - No space before
(in calls:foo(x)notfoo (x) - Space after commas:
c(1, 2, 3) - Space after control flow:
if (,for (,while (
Function Definitions
Short signatures stay on one line. Long signatures wrap with continuation indent. Opening brace on its own line.
1# Short
2lapply <- function (X, FUN, ...)
3{
4 FUN <- match.fun(FUN)
5 ...
6}
7
8# Long (default: paren alignment)
9lm <- function (formula, data, subset, weights, na.action, method = "qr",
10 model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
11 singular.ok = TRUE, contrasts = NULL, offset, ...)
12{
13 ...
14}
15
16# Long (wrap = "fixed": 8-space indent)
17lm <- function (formula, data, subset, weights, na.action,
18 method = "qr", model = TRUE, x = FALSE, y = FALSE,
19 qr = TRUE, singular.ok = TRUE, contrasts = NULL, offset, ...)
20{
21 ...
22}
Inline If-Else
Preserved by default (R Core compatible). Use expand_if = TRUE to expand:
1# Default: preserved
2x <- if (a) b else c
3
4# With expand_if = TRUE
5if (a) {
6 x <- b
7} else {
8 x <- c
9}
Philosophy
This formatter follows tinyverse principles. The only dependency is utils::getParseData() for tokenization.
License
GPL-3
Reference
See Function Reference for complete API documentation.
Functions
rformat Reference
Function reference for rformat