पाठ 24 / 25
Workflow: Projects, Version Control, Testing and Packages
Organise R work professionally with projects, Git, tests and packages.
Professional R habits
Analysis code deserves the same care as software. Use projects with a consistent layout (data/raw, data/processed, R/ for functions, analysis/ or reports/, output/), relative paths (the here package's here::here("data", "raw.csv") helps), and never modify raw data by hand: clean it in code. Put the project under Git version control (RStudio and Positron integrate it) and lock package versions with renv. Move repeated code into functions in R/ files. Test functions with testthat (test_that("...", { expect_equal(...) })). When functions are reused across projects, turn them into an R package: usethis creates the structure (usethis::create_package()), roxygen2 generates documentation from comments, devtools builds, loads and checks it (devtools::check()), and packages can be shared internally or on CRAN. Style code consistently with the tidyverse style guide, automated by styler and checked by lintr. For pipelines with many steps, the targets package rebuilds only outdated steps, like a Makefile for analyses.
Tests for an analysis function and package scaffolding
testthat checks behaviour; usethis and devtools manage packages.
# R/gst.R
gst_total <- function(amount, rate = 0.18) {
stopifnot(is.numeric(amount), rate >= 0)
round(amount * (1 + rate), 2)
}
# tests/testthat/test-gst.R
library(testthat)
test_that("gst_total adds the default 18% GST", {
expect_equal(gst_total(100), 118)
expect_equal(gst_total(c(100, 200)), c(118, 236))
})
test_that("gst_total rejects non-numeric input", {
expect_error(gst_total("100"))
})
# turning reusable code into a package
# usethis::create_package("~/code/salestools")
# usethis::use_r("gst")
# usethis::use_testthat()
# devtools::document() # roxygen2 comments -> help pages
# devtools::test()
# devtools::check() # full package checks, as CRAN runs themRaw data is read-only
Keep raw files untouched and write every cleaning step in code. If someone asks how a number was produced, you can show the exact path from source to result.
त्वरित जाँच: Which package is commonly used for writing unit tests in R?
- testthat
- ggplot2
- lubridate
- shiny
Answer
testthat — testthat provides expect_* functions and is the standard for R tests.