Dynamic Reporting with R Markdown and Knitr
R Markdown, powered by the knitr engine, lets you combine narrative text, live R code, and its output into a single reproducible document — rendered as HTML, PDF, or Word with one click.
1. Installing R Markdown
install.packages("rmarkdown")
# For PDF output, you also need a LaTeX distribution:
install.packages("tinytex")
tinytex::install_tinytex()
2. Creating an R Markdown File
In RStudio: File → New File → R Markdown. This generates a .Rmd file with a YAML header, narrative text, and embedded "code chunks."
---
title: "Sales Analysis Report"
author: "Your Name"
date: "2026-07-18"
output: html_document
---
## Introduction
This report analyzes quarterly sales performance.
```{{r setup, include=FALSE}}
library(dplyr)
library(ggplot2)
sales <- read.csv("data/sales.csv")
```
## Summary Statistics
```{{r}}
summary(sales$revenue)
```
## Revenue Trend
```{{r, echo=FALSE}}
ggplot(sales, aes(x = month, y = revenue)) +
geom_line() + theme_minimal()
```
3. Code Chunk Options
| Option | Effect |
|---|---|
| echo=FALSE | Hide the R code, show only its output |
| include=FALSE | Run the code but hide both code and output |
| eval=FALSE | Show the code but don't execute it |
| message=FALSE | Suppress package loading messages |
| fig.width / fig.height | Control the size of generated plots |
4. Rendering ("Knitting") the Document
Click the Knit button in RStudio, or run from the console:
rmarkdown::render("report.Rmd", output_format = "html_document")
5. Multiple Output Formats
---
output:
html_document: default
pdf_document: default
word_document: default
---
With multiple formats listed, you can render each specifically:
rmarkdown::render("report.Rmd", output_format = "pdf_document")
rmarkdown::render("report.Rmd", output_format = "word_document")
6. Inline R Code
Embed live values directly inside sentences using backticks:
The average revenue this quarter was `r round(mean(sales$revenue), 2)` dollars,
across `r nrow(sales)` recorded transactions.
7. Tables with knitr::kable()
library(knitr)
kable(head(sales), caption = "Sample of Sales Data")
8. Why Reproducibility Matters
Because the report re-runs the actual R code every time it's knitted, your narrative, tables, and charts can never silently fall out of sync with your data — unlike a manually copy-pasted report.
9. Production-Ready Checklist
- ✅ Structure your .Rmd with a clear YAML header — title, author, date, output format.
- ✅ Use chunk options deliberately — echo, include, eval — to control what readers see.
- ✅ Use inline R code — for numbers that stay in sync with your data.
- ✅ Knit to multiple formats — HTML for interactivity, PDF/Word for sharing.
Ready to master R Programming?
Build real-world data analysis and visualization projects with hands-on training, mentor-led sessions, and placement support.
.png)