Skip to Content
Course content

37: Building an Automated Statistical Report

Click on the "Edit" button in the top corner of the screen to edit your slide content.

How do I actually "automate" the report? Do I have to run every chunk manually?

The short answer is no. If you're clicking "Run Chunk" over and over, you're just writing a script in a fancy editor. To truly automate, we use Quarto (or R Markdown). The magic is that the report becomes a single source of truth: a .qmd file that contains both your narrative and your code.

Imagine you're tasked with a monthly "Customer Churn Analysis." Instead of copying a plot into a PowerPoint slide, you write a Quarto document. When the new month's data hits your folder, you just "Render" the document. R executes every block of code from top to bottom, pulls the latest data, and spits out a polished HTML or PDF file. Here is a glimpse of how a chunk in that report looks:

```{r}
#| label: churn-summary
#| echo: false

library(tidyverse)
data <- read_csv("monthly_churn_data.csv")

summary_table <- data %>%
  group_by(plan_type) %>%
  summarise(churn_rate = mean(churned))

knitr::kable(summary_table, caption = "Churn Rate by Plan Type")
```

Notice the echo: false option. That's a lifesaver. It tells R, "Run this code to get the table, but don't show the actual code to the executives reading the report." They want the insight, not the syntax.

What's the best way to handle reports that need to change based on a variable, like a specific region or month?

You don't want to create twelve different files for twelve different months. I've seen engineers do this, and it's a maintenance nightmare. Instead, you use parameters.

By defining a params section in your YAML header, you turn your report into a template. You can then pass different values into that template using a separate R script. It looks like this in your Quarto header:

---
title: "Regional Performance Report"
format: html
params:
  region: "North America"
---

Now, inside your code chunks, you don't hardcode "North America"; you use params$region. To generate reports for every region in your company, you just write a small loop in a standard R script:

regions <- c("North America", "EMEA", "APAC", "LATAM")

for (r in regions) {
  quarto::quarto_render(
    "report_template.qmd", 
    execute_params = list(region = r),
    output_file = paste0("Report_", r, ".html")
  )
}

This is where the "software engineering" side of R really kicks in. You've just turned a manual reporting task into a scalable pipeline.

Can I actually schedule this to run on its own, or do I still have to click "Render" every time?

If you're still clicking a button, it's "semi-automated." To get to full automation, you need to move the execution outside of the RStudio IDE. I usually recommend one of two paths depending on your infrastructure.

If you're on a Linux server or a Mac, cron is your best friend. You create a shell script that calls Rscript to run the loop I showed you above. If you're in a modern DevOps environment, GitHub Actions is a fantastic way to do this—you can trigger a report to build every time data is pushed to a repository.

A simple wrapper script (let's call it run_reports.R) would look like this:

# Load libraries needed for the render process
library(quarto)

# Logic to check if data exists before wasting resources
if (file.exists("data/latest_metrics.csv")) {
  quarto::quarto_render("automated_analysis.qmd")
  message("Report successfully generated at ", Sys.time())
} else {
  stop("Data file missing! Report failed.")
}

Once this script is set up, you just schedule it. You stop being the "person who makes the report" and start being the "person who maintains the system that makes the report." Trust me, your Fridays will be much quieter.




📋 Practical Task

Exercise: Building a Parameterized Quarterly Sales Generator

You have been given a dataset sales_data.csv with columns quarter (Q1, Q2, Q3, Q4), revenue, and expenses. Your goal is to build an automated system that generates four separate reports—one for each quarter.

  • Step 1: Create a Quarto file quarterly_report.qmd. In the YAML header, define a parameter called target_quarter with a default value of "Q1".
  • Step 2: Inside the .qmd file, write a code chunk that filters the sales_data.csv based on params$target_quarter and calculates the total profit (revenue minus expenses).
  • Step 3: Create a separate R script generate_all.R. In this script, create a vector containing all four quarters and use a for loop with quarto::quarto_render() to generate four distinct HTML files named Report_Q1.html, Report_Q2.html, and so on.
  • Step 4: Run the generate_all.R script and verify that four separate reports were created in your directory, each displaying the correct data for its respective quarter.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.