Format R Code
Description
Format R code string according to base R style conventions.
Usage
1rformat(code, indent = 4L, line_limit = 80L, wrap = "paren",
2 brace_style = "kr", control_braces = FALSE, expand_if = FALSE,
3 else_same_line = TRUE, function_space = FALSE, join_else = TRUE)
Arguments
code: Character string of R code to format.indent: Indentation per level: integer for spaces (default 4), or character string for literal indent (e.g.,"\t\t"for vintage R Core style).line_limit: Maximum line length before wrapping (default 80).wrap: Continuation style for long function signatures:"paren"(default) aligns to opening parenthesis,"fixed"uses 8-space indent.brace_style: Brace placement for function definitions:"kr"(default) puts opening brace on same line as) {,"allman"puts it on a new line.control_braces: If TRUE, add braces to bare one-line control flow bodies (e.g.,if (x) ybecomesif (x) { y }). Default FALSE matches R Core source code where 59% of control flow bodies are bare.expand_if: Expand inline if-else to multi-line (default FALSE).else_same_line: If TRUE (default), repair top-level}\nelse(which is a parse error in R) by joining to} elsebefore formatting. When FALSE, unparseable input is returned unchanged with a warning.function_space: If TRUE, add space before(in function definitions:function (x)instead offunction(x). Default FALSE matches 96% of R Core source code.join_else: If TRUE (default), moveelseto the same line as the preceding}:} else {. Matches R Core source code where 70% use same-line else. When FALSE,}\nelseon separate lines is preserved.
Value
Formatted code as a character string.
Examples
1# Basic formatting: spacing around operators
2rformat("x<-1+2")
3
4# Add braces to bare control-flow bodies
5rformat("if(x>0) y<-1", control_braces = TRUE)
6
7# Expand inline if-else to multi-line
8rformat("x <- if (a) b else c", expand_if = TRUE)
9
10# Wrap long function signatures (default: paren-aligned)
11long_sig <- paste0(
12 "f <- function(alpha, beta, gamma, delta, ",
13 "epsilon, zeta, eta) {\n 1\n}")
14cat(rformat(long_sig), sep = "\n")
15
16# Wrap with fixed 8-space continuation indent
17cat(rformat(long_sig, wrap = "fixed"), sep = "\n")
18
19# Allman brace style
20rformat("f <- function(x) { x }", brace_style = "allman")