Reporting and Communication
12 min read
Reporting and Communication with R 📊
Welcome to the exciting world of telling stories with your data! Just collecting and analyzing data is like gathering all the ingredients for a delicious cake but never actually baking it and sharing it with anyone. The real magic happens when you can communicate your findings in a clear, reproducible, and professional way. This section of our R course will turn you into a data storyteller.
1. Introduction to R Markdown and Quarto 📝
The Problem: Imagine you've just completed a brilliant data analysis. You have your R code, a bunch of plots, and some insightful conclusions. Now, you need to share this with your team, your boss, or the world. The old way? Copy-pasting your plots into a Word document, manually typing up your findings, and then crying softly when you realize you have to rerun the whole analysis because of a tiny data change. This process is tedious, error-prone, and makes reproducibility a nightmare.
The Solution: R Markdown and Quarto are here to save the day! They are tools that let you create dynamic documents that combine your R code, its output (like plots and tables), and your written text all in one place. Think of it as a smart notebook that automatically updates your entire report whenever your data or code changes.
What is R Markdown?
R Markdown is a file format for making dynamic documents with R. It's a plain text file with the extension .Rmd. You write your narrative using simple Markdown syntax (like the one used in many web forums and text editors) and embed your R code in special "chunks." When you "knit" the document, R runs the code, takes the results, and combines them with your text to produce a polished final document.
And What's this Quarto Thing?
Quarto is the next generation of R Markdown. It's built on the same principles but is designed to be multi-language and multi-engine. While R Markdown is fantastic, it's very R-centric. Quarto, on the other hand, can easily work with Python, Julia, and Observable JS right out of the box. It's the future of scientific and technical publishing. For our purposes, the concepts are very similar, and learning one will make the other feel incredibly familiar. We'll start with the ideas that are common to both.
Interesting Fact: The idea of weaving code and text together is not new! It's based on a concept called "literate programming," introduced by the legendary computer scientist Donald Knuth in the 1980s. He believed that programs should be written more for humans to read than for computers to execute.
Getting Started: Installation 🛠️
The best way to work with R Markdown and Quarto is through the RStudio IDE, which has excellent built-in support.
- Install R and RStudio: If you haven't already, you'll need the latest versions of R and the RStudio IDE.
- Install
rmarkdownpackage:rinstall.packages("rmarkdown") - For Quarto: RStudio usually comes with Quarto bundled. You can check if it's installed and its version by opening the "Terminal" tab in RStudio and typing:If it's not there, you can download and install it from the official Quarto website.bash
quarto --version
Your First R Markdown/Quarto Document
Let's create a simple document to see how it works.
In RStudio, go to
File > New File > R Markdown...(orQuarto Document...).A dialog box will appear. You can give your document a title and author name. Select the default output format (HTML is a great start).
RStudio will generate a template file for you. It looks something like this:
markdown--- title: "My First Report" author: "Data Wizard" date: "2026-02-25" format: html --- ## R Markdown This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. ## Including R Code You can include R code in the document as follows: ```{r cars} summary(cars)Including Plots
You can also embed plots, for example:
{rplot(pressure)Note that the
echo = FALSEparameter was added to the code chunk to prevent printing of the R code that generated the plot.textClick the Render (or Knit) button in RStudio. Voila! You'll see a beautifully formatted HTML document appear, with your text, the summary output from the
carsdataset, and the plot of thepressuredataset.
This simple file has three main components:
- The YAML Header: The text at the very top enclosed in
---. This is where you put metadata like the title, author, and desired output format. - Text: Your narrative, written in Markdown.
- Code Chunks: The sections enclosed in
```{r} ... ```. This is where your live R code goes.
2. Weaving Text and Code: Chunk Options and Inline R 🧶
Now that we've seen the basic structure, let's get into the details of how to control our R code within the document.
The Problem: You don't always want to show your code. Sometimes you just want the plot, or maybe you want to show the code but not run it. How do you control the appearance and behavior of your code chunks? Also, what if you want to mention a specific number from your R analysis directly in your text, like "The average miles per gallon is 20.09"? Typing this manually is risky; if the data changes, you have to remember to update your text.
The Solution: Code chunk options and inline R code are the answers!
Code Chunk Options
You can add options to the header of a code chunk (````{r chunk-name, option1=value1, option2=value2}``) to control its behavior. Here are some of the most frequently used options in the industry:
echo: Controls whether the R code itself is displayed in the final document.echo = TRUE: (The default) Show the code.echo = FALSE: Hide the code. Perfect for reports for non-technical audiences who only care about the results.
eval: Controls whether the R code is executed.eval = TRUE: (The default) Run the code.eval = FALSE: Do not run the code. Useful for showing example code that might take a long time to run or is for demonstration purposes only.
include: Controls whether the code and its output are included in the final document.include = TRUE: (The default) Include everything.include = FALSE: Run the code, but don't show the code or its output in the document. This is great for setup code that loads packages or data but doesn't produce any output you want to show.
warningandmessage: Controls whether to display any warnings or messages that R produces.warning = FALSEandmessage = FALSE: Hide warnings and messages for a cleaner report.
fig.cap: Adds a caption to your plot.fig.widthandfig.height: Control the dimensions of your plots (in inches).
Example in action:
---
title: "Controlling My Code"
format: html
---
Here is a demonstration of some chunk options.
### Showing Code and Output (Default)
```{r default-behavior}
# This code and its output will be shown
data(iris)
head(iris)Hiding the Code, Showing the Output
Sometimes, you just want to show the beautiful plot, not the messy code that made it.
plot(iris$Petal.Length, iris$Petal.Width,
main = "Iris Petal Dimensions")Showing Code, But Not Running It
This is useful for tutorials or explaining a function.
# This is an example of a function that would take a long time to run.
# We set eval=FALSE so the document renders quickly.
# long_running_function(my_data)Running Code, But Hiding Everything
We can load our libraries here. The reader doesn't need to see this part.
library(ggplot2)Inline R Code
To solve the problem of mentioning data-driven numbers in your text, you can use inline R code. The syntax is `r R_code`.
Imagine you've calculated the mean of the mpg column in the mtcars dataset. Instead of typing the number manually, you can do this:
We loaded the `mtcars` dataset to analyze vehicle performance.
Our analysis shows that the average miles per gallon for these cars is `r round(mean(mtcars$mpg), 2)`.When you render this document, R will run round(mean(mtcars$mpg), 2), get the result (which is 20.09), and place it directly into your sentence. Now your report is truly dynamic!
3. Rendering Documents: Exporting to HTML, PDF, and Word 📤
The Problem: You've created a fantastic .Rmd or .qmd file. But you can't exactly email that file to your CEO and expect them to know what to do with it. You need to convert your document into a standard, professional format that anyone can open.
The Solution: R Markdown and Quarto can render your single source file into a variety of formats, including HTML, PDF, and Microsoft Word.
You can specify the output format in the YAML header.
HTML Documents
This is often the default and most versatile format. HTML files are great for web pages, reports with interactive elements, and general sharing.
---
title: "My Awesome Report"
author: "Me"
format: html
---Under the Hood: When you render to HTML, R Markdown works with a tool called Pandoc (a universal document converter) to turn your Markdown text and R output into a self-contained HTML file. This means all your images and styling are bundled right into the one file, making it super easy to share.
PDF Documents
PDF is the king for formal reports, academic papers, and anything you intend to be printed. It provides precise control over the layout.
---
title: "My Formal Report"
author: "Me"
format: pdf
---Getting it to work: Rendering to PDF requires a LaTeX distribution to be installed on your computer. LaTeX is a typesetting system that is the gold standard for scientific and mathematical documents.
- For R users, the easiest way to get this is with the
tinytexR package. It's a lightweight and easy-to-manage LaTeX distribution.You only need to do this once! After that, rendering to PDF should just work.rinstall.packages("tinytex") tinytex::install_tinytex()
Funny Exaggeration: Trying to render a PDF without LaTeX is like trying to bake a cake without an oven. You have all the ingredients (your .Rmd file), but you're missing the fundamental tool to transform it into the final product.
Word Documents (.docx)
Sometimes, you have to work with colleagues who live and breathe Microsoft Word. Fear not! You can export directly to a .docx file.
---
title: "My Collaborative Report"
author: "Me"
format: docx
---This is incredibly useful because your colleague can then use "Track Changes" and add comments to the document you sent them. Pandoc does the heavy lifting of converting your report into a format that Word understands.
You can render to a specific format by changing the format line in the YAML header and clicking the Render button. You can even specify multiple formats at once!
---
title: "My Multi-format Report"
author: "Me"
format:
html: default
pdf: default
---4. A Taste of Interactivity: Introduction to Shiny ✨
The Problem: Your static reports are great, but what if you wanted your audience to interact with the data? What if they could change a filter, select a different variable for a plot, or see how a model's prediction changes when they adjust an input? A static plot can only tell one story, but an interactive app can tell thousands.
The Solution: Meet Shiny! Shiny is an R package that makes it easy to build interactive web applications straight from R. No web development skills (HTML, CSS, JavaScript) are required to get started.
Think of it this way: R Markdown is for creating a beautiful, finished painting. Shiny is for giving your audience the paintbrush and letting them explore the canvas themselves.
How Shiny Works: The Two-Part Structure
A Shiny app has two main components:
The User Interface (UI): This is the front-end, the part the user sees and interacts with. It defines the layout of your app, including where the sliders, dropdown menus, plots, and text go. You define the UI as an object, usually called
ui.The Server: This is the back-end, the "brain" of your app. It's an R function, usually called
server, that listens for changes in the UI (e.g., a user moving a slider). When a change happens, it reruns parts of your R code and sends the updated outputs (like a new plot or number) back to the UI.
This separation is key. The UI is just the blueprint for the webpage. The server function contains the instructions for how to bring that blueprint to life with your data.
Your First "Hello, Shiny!" App
Let's build the simplest possible Shiny app. In RStudio, go to File > New File > Shiny Web App.... Name it my_first_app and choose the "Single File (app.R)" option.
RStudio will give you a template. Here is a simplified version of it:
# Load the shiny package
library(shiny)
# 1. Define the User Interface (UI)
ui <- fluidPage(
# App title
titlePanel("Hello Shiny!"),
# A sidebar with a slider for the number of bins in the histogram
sidebarLayout(
sidebarPanel(
sliderInput(inputId = "bins",
label = "Number of bins:",
min = 1,
max = 50,
value = 30)
),
# The main panel to display the histogram
mainPanel(
plotOutput(outputId = "distPlot")
)
)
)
# 2. Define the Server logic
server <- function(input, output) {
# This part creates the histogram
# It will re-run automatically whenever the user changes the "bins" slider
output$distPlot <- renderPlot({
x <- faithful$waiting
bins <- seq(min(x), max(x), length.out = input$bins + 1)
hist(x, breaks = bins, col = "#75AADB", border = "white",
xlab = "Waiting time to next eruption (in mins)",
main = "Histogram of waiting times")
})
}
# 3. Create and run the Shiny app
shinyApp(ui = ui, server = server)Click the Run App button in RStudio. A window will pop up with your interactive app! You'll see a histogram and a slider. Try moving the slider—the plot updates instantly. This is the magic of Shiny. You've just created a dynamic, interactive data visualization without writing a single line of web code.
This is just a tiny glimpse into the power of Shiny, but it demonstrates the core concept: connecting user inputs (input$bins) to R-generated outputs (output$distPlot).
Further Reading and References 📚
- Official R Markdown Documentation: R Markdown: The Definitive Guide
- Official Quarto Documentation: Quarto Get Started
- Pandoc, the Universal Converter: Pandoc Website
- The
tinytexPackage: tinytex on CRAN - Official Shiny Documentation and Tutorials: Shiny from RStudio
Challenge
Challenge: Crafting a Dynamic Data Report with Quarto
You are tasked with creating a reproducible report analyzing the classic iris dataset, which is built into R. Your entire report must be contained within a single Quarto (.qmd) file. Follow the requirements below precisely.
Requirements:
YAML Header:
- Set the document title to
Iris Dataset Analysis. - Set the author to your name.
- Configure the document to render both
htmlandpdfoutput formats.
- Set the document title to
Narrative and Inline Code:
- Write an introductory paragraph that starts with:
This report provides a brief analysis of the iris dataset. - In the same paragraph, dynamically report the total number of observations in the dataset by embedding inline R code.
- Write an introductory paragraph that starts with:
Code Chunks:
- Chunk 1 (Setup): Create a code chunk that loads the
ggplot2library. This entire chunk (both the code and any resulting messages/output) should be completely hidden from the final rendered document. - Chunk 2 (Data Preview): Create a code chunk that contains the code to display the first 6 rows of the
irisdataset using thehead()function. For this chunk, only the R code itself should be visible in the final report; the code should not be executed. - Chunk 3 (Summary Statistics): Create a code chunk that calculates and displays a statistical summary of the
irisdataset using thesummary()function. In the final report, the output of this chunk (the summary table) must be visible, but the R code used to generate it must be hidden. - Chunk 4 (Visualization): Create a code chunk to generate a scatter plot using
ggplot2. The plot should mapSepal.Lengthto the x-axis andPetal.Lengthto the y-axis, with points colored bySpecies. The R code for this chunk must be visible, but any potential warnings it generates must be suppressed. Finally, add a figure caption to the plot that reads:"Sepal Length vs. Petal Length by Species".
- Chunk 1 (Setup): Create a code chunk that loads the
Expected result
Your final output should be a single block of text representing a complete .qmd file. It must correctly implement all specified YAML metadata, inline R code, and code chunks with their respective options.
Example of a correct solution:
---
title: "Iris Dataset Analysis"
author: "Your Name"
format:
html: default
pdf: default
---
## Introduction
This report provides a brief analysis of the iris dataset. The dataset contains `r nrow(iris)` observations.
## Data Analysis
```{r setup, include=FALSE}
library(ggplot2)head(iris)summary(iris)ggplot(iris, aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
geom_point()