r-best-practices

star 0

Idiomatic R coding standards for statistical analysis. Use when writing R functions, using tidyverse/data.table, or structuring analysis scripts.

ntluong95 By ntluong95 schedule Updated 3/7/2026

name: R Best Practices description: Idiomatic R coding standards for statistical analysis. Use when writing R functions, using tidyverse/data.table, or structuring analysis scripts. metadata: labels: [r-language, best-practices, tidyverse, vectorization] triggers: files: ['/*.R', '/*.Rmd'] keywords: [function, library, source, vectorize, tidyverse, pipe]


R Best Practices

Priority: P0 (FOUNDATIONAL)

๐Ÿ“ฆ Package Management

  • library() only: Never require() in scripts. Use library() at script top.
  • Explicit namespacing: Use pkg::fun() to avoid namespace collisions. Always for infrequent calls.
  • Minimal dependencies: Prefer base R when equivalent. Import only what you use.

โšก Vectorization

  • Rule: If you write a for loop on data, you're probably doing it wrong.
  • apply family: sapply, vapply, lapply, mapply for list/matrix operations.
  • purrr: map(), map_dbl(), map_dfr() for type-stable functional programming.
  • data.table: Use [i, j, by] syntax for grouped operations on large datasets.
  • Vectorize(): Wrap scalar functions for vector input when needed.

๐ŸŽฏ Functional Programming

  • Pure functions: No side effects. Same input โ†’ same output. Explicit return().
  • No global assignment: Never use <<- in functions. Return values instead.
  • Closures: Use factory functions for parameterized behavior.
  • purrr::safely(): Wrap functions that may fail to capture errors without stopping.

๐Ÿ“ Code Style (tidyverse Guide)

  • snake_case for all names. PascalCase only for R6 classes.
  • <- for assignment. Reserve = for function arguments only.
  • Spacing: Space after commas, around <-, after #. No space before ( in function calls.
  • Braces: { on same line, } on own line. Always use braces, even for one-liners.
  • Line length: Max 80 characters.
  • Tools: Enforce with styler::style_file() and lintr::lint().

๐Ÿ—„ Memory Management

  • Remove large objects: rm(large_df); gc() after processing.
  • Chunked reading: data.table::fread() with select for column subsetting.
  • .RData avoidance: Never save/load .RData. Use explicit saveRDS()/readRDS().

๐Ÿ“š References

Install via CLI
npx skills add https://github.com/ntluong95/agent-skills-dlnm --skill r-best-practices
Repository Details
star Stars 0
call_split Forks 0
navigation Branch main
article Path SKILL.md
More from Creator