Skip to main content

12. Reproducible Workflows: R Markdown, Git Version Control, and Package Development

 

reproducible workflows, R Markdown, GitHub, R packages, devtools, data science reproducibility

Reproducibility is the cornerstone of trustworthy data science. A fully reproducible workflow lets you regenerate analyses on demand, share results with colleagues, and ensure that your findings stand the test of time. In this post, we’ll explore three pillars of reproducible R workflows:

  1. R Markdown for dynamic, multi-format reports (HTML, PDF, Word)

  2. Git and GitHub for version control and collaboration

  3. Building R packages with devtools to package and distribute your code

By the end, you’ll have a blueprint for structuring projects that are transparent, maintainable, and easily shareable.

1. R Markdown for Dynamic Reporting

R Markdown bridges code and narrative in a single document. It weaves together prose, executable R chunks, and output—tables, plots, and model summaries—into one coherent report. You can render to HTML, PDF, and Word with a single command.

1.1 Creating an R Markdown Document

In RStudio:

  1. File → New File → R Markdown…

  2. Enter a title, author, and default output format (you can override this later).

  3. Save the file with .Rmd extension.

A basic template looks like:

markdown
---
title: "My Analysis"
author: "Your Name"
date: "`r Sys.Date()`"
output:
  html_document:
    toc: true
    theme: flatly
  pdf_document: default
  word_document: default
---

# Introduction

This report explores…

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  message = FALSE,
  warning = FALSE
)
library(tidyverse)

Data Import

{r data-import}
df <- read_csv("data/raw/dataset.csv")
glimpse(df)
Codice

### 1.2 YAML Header and Output Formats

The YAML at the top controls:

- **output**: which formats to generate  
- **toc**: table of contents  
- **theme**: Bootstrap theme for HTML  
- **latex_engine**: for PDF (`xelatex`, `pdflatex`)  

You can render only one format with:

```r
rmarkdown::render("report.Rmd", output_format = "pdf_document")

1.3 Parameterized Reports

Convert your Rmd into a template that accepts parameters:

yaml
params:
  year:
    value: 2023
    label: "Analysis Year"

In the body:

{r filter-year}
df <- df %>% filter(year == params$year)

Render with a different year:

r
rmarkdown::render("report.Rmd", params = list(year = 2022))

1.4 Best Practices for R Markdown

  • Store raw data and scripts in separate folders (data/, R/).

  • Use here::here() to build file paths, avoiding hardcoded directories.

  • Modularize long reports by splitting into child documents:

    markdown
    ```{r child="sections/data-prep.Rmd"}
    
  • Version control your .Rmd files (see section 2).

  • Knit regularly to catch errors early.

2. Git and GitHub for Version Control

Tracking changes and collaborating smoothly hinges on version control. Git records every commit—snapshots of your project—while GitHub provides remote hosting, issue tracking, and pull requests.

2.1 Initializing a Git Repository

In your project root:

bash
git init
git add .
git commit -m "Initial commit with R Markdown template"

2.2 .gitignore for R Projects

Create a .gitignore to exclude large or sensitive files:

Codice
# R
.Rproj.user/
.Rhistory
.RData
.Ruserdata
renv/library/
renv/python/
# MacOS
.DS_Store
# Logs and caches
logs/
*.log

2.3 Branching and Collaboration

  • Create a feature branch:

    bash
    git checkout -b feature/data-cleaning
    
  • Commit incremental changes:

    bash
    git add R/data_prep.R
    git commit -m "Clean and normalize raw data"
    
  • Push and open a pull request on GitHub:

    bash
    git push -u origin feature/data-cleaning
    

2.4 Tagging and Releases

When you hit a stable milestone:

bash
git tag -a v1.0 -m "First reproducible analysis"
git push --tags

On GitHub, create a Release for versioned artifacts.

2.5 Continuous Integration

Automate rendering and testing with GitHub Actions:

yaml
name: R-CMD-check

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: r-lib/actions/setup-r@v2
      - name: Install dependencies
        run: Rscript -e 'install.packages(c("rmarkdown", "devtools", "testthat"))'
      - name: Render report
        run: Rscript -e 'rmarkdown::render("report.Rmd", quiet = TRUE)'

This pipeline ensures that every push can generate your R Markdown reports without manual intervention.

3. Building R Packages with devtools

Turning your analysis code into an R package promotes reuse, documentation, and distribution. devtools streamlines package creation.

3.1 Setting Up a Package Skeleton

In R:

r
install.packages("devtools")
devtools::create("myAnalysisPackage")

This creates a directory myAnalysisPackage/ with:

  • DESCRIPTION: metadata (Title, Version, Author, Dependencies)

  • NAMESPACE: exported functions

  • R/: folder for your R scripts

3.2 Documenting with roxygen2

Write documentation above each function using roxygen tags:

r
#' Summarize Data by Group
#'
#' @param df A data frame.
#' @param group_col Column name to group by (string).
#' @return A tibble with group counts and means.
#' @export
summarize_group <- function(df, group_col) {
  df %>%
    dplyr::group_by(.data[[group_col]]) %>%
    dplyr::summarize(count = dplyr::n(), .groups = "drop")
}

Generate documentation and NAMESPACE:

r
devtools::document()

3.3 Testing with testthat

Include a tests/testthat/ folder. Example test file:

r
test_that("summarize_group works", {
  df <- tibble(a = c("x", "y", "x"), val = 1:3)
  res <- summarize_group(df, "a")
  expect_equal(nrow(res), 2)
  expect_true("count" %in% names(res))
})

Run tests:

r
devtools::test()

3.4 Building and Installing

Build the package tarball:

r
devtools::build()

Install locally:

r
devtools::install()

Now you can load with library(myAnalysisPackage) and use your functions.

3.5 Sharing on GitHub or CRAN

  • Push your package directory to a GitHub repository.

  • For wider distribution, follow CRAN’s submission guidelines: check with devtools::check(), ensure no errors or warnings, then devtools::release().

Conclusion and Next Steps

You’ve now mastered three pillars of reproducible workflows:

  • Generating dynamic, parameterized reports in HTML, PDF, and Word with R Markdown

  • Tracking code changes, collaborating, and automating tasks using Git and GitHub

  • Packaging your analysis code into shareable R packages with devtools

In the next chapter, we’ll extend these foundations by exploring package ecosystems and advanced optimization techniques. If you have questions about R Markdown nuances, Git best practices, or package development pitfalls, leave a comment below. Let’s build reproducible, transparent, and durable data science together!

Comments

Popular posts from this blog

Alfred Marshall – The Father of Modern Microeconomics

  Welcome back to the blog! Today we explore the life and legacy of Alfred Marshall (1842–1924) , the British economist who laid the foundations of modern microeconomics . His landmark book, Principles of Economics (1890), introduced core concepts like supply and demand , elasticity , and market equilibrium — ideas that continue to shape how we understand economics today. Who Was Alfred Marshall? Alfred Marshall was a professor at the University of Cambridge and a key figure in the development of neoclassical economics . He believed economics should be rigorous, mathematical, and practical , focusing on real-world issues like prices, wages, and consumer behavior. Marshall also emphasized that economics is ultimately about improving human well-being. Key Contributions 1. Supply and Demand Analysis Marshall was the first to clearly present supply and demand as intersecting curves on a graph. He showed how prices are determined by both what consumers are willing to pay (dem...

“This Sentence Is False”: The Liar Paradox, from Ancient Crete to Modern Code

 “All Cretans are liars,” said the Cretan Epimenides.  “This sentence is false,” echoes every logic textbook.  We’re still arguing 2,600 years later—and the paradox is winning.   _____________________________  /                             \ |   “THIS SENTENCE IS FALSE.”  |  \_____________________________/               |               |  self-reference               v    +---------------------------+    |  Truth flips back on     |    |  itself — paradox loop!  |    +---------------------------+ 1. Meet the Liar The classic one-liner: L: “This sentence is false.” If L is true, then what it asserts—its own falsity—must hold, so L is false. If L is false, then what it asserts isn’t the ca...

Fundamental Analysis Case Study NVIDIA

  Executive summary NVIDIA is analyzed here using the full fundamental framework: balance sheet, income statement, cash flow statement, valuation multiples, sector comparison, sensitivity scenarios, and investment checklist. The company shows exceptional profitability, strong cash generation, conservative liquidity and net cash, and premium valuation multiples justified only if high growth and margin profiles persist. Key investment considerations are growth sustainability in data center and AI, margin durability, geopolitical and supply risks, and valuation sensitivity to execution. The detailed numerical work below uses the exact metrics you provided. Company profile and market context Business model and market position Company NVIDIA Corporation, leader in GPUs, AI accelerators, and related software platforms. Core revenue streams : data center GPUs and systems, gaming GPUs, professional visualization, automotive, software and services. Strategic advantage : GPU architecture, C...