How to use Rmarkdown
This post is a quick guide to setting up an R Markdown file so everything runs smoothly from the start. It assumes you’ve already installed R, RStudio, and the rmarkdown package. Once that’s done, open RStudio and go to File → New File → R Markdown to create a new document.
I’ll share the essential setup code at the top, then walk you through what each part does. Just copy and paste the code below, and you’ll be up and running in no time!
---
title: "Default Rmarkdown Template"
author: "Jack Auty"
date: "`r Sys.Date()`"
output:
html_document:
toc: true
toc_title: "Table of Contents"
number_sections: true
---
```{r CSS install, include=T, results='asis', comment=NA, echo=F}
x <- tryCatch(readLines("https://raw.githubusercontent.com/JackAuty/RmarkdownStyle/main/styles.css"), error=function(e) ""); if (length(x)) cat("<style>\n", paste(x, collapse="\n"), "\n</style>")
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE, # Show code
warning = FALSE, # Suppress warnings
message = FALSE # Suppress messages
)
options(scipen =999 )
```
# Load Required Packages
```{r load-packages, warning=FALSE, message=FALSE, results='hide' }
# Load packages, install if required
packages <- c("ggplot2", "viridisLite", "sjPlot")
invisible(lapply(packages, function(pkg) {
if (!requireNamespace(pkg, quietly = TRUE)) install.packages(pkg)
library(pkg, character.only = TRUE)
}))
```
# Citations
```{r}
# Use the existing package list
pkg <- packages
# Create a character vector for clean citations
citation_list <- character()
# Loop through each package and clean citation
for (i in pkg) {
# Get the plain text citation
raw <- paste(capture.output(print(citation(i), style = "text", bibtex = FALSE)), collapse = "\n")
# Clean: remove _, *, " and trailing . or ,.
clean <- gsub("_", "", raw, fixed = TRUE)
clean <- gsub("\\*", "", clean)
clean <- gsub('\\"', "", clean) # Handles escaped quotes
clean <- gsub('"', "", clean) # Handles regular quotes
clean <- gsub("\\\\texttt\\{(.*?)\\}", "\\1", clean)
clean <- gsub(", \\.$", "", clean)
clean <- gsub("\\s*\\.$", "", clean)
clean <- gsub("[\u201C\u201D]", "", clean)
clean <- trimws(clean)
# Append to citation list
citation_list <- c(citation_list, clean)
}
# Display as a table
sjPlot::tab_df(
data.frame(References = citation_list),
col.header = "References",
sep = " "
)
```
# Load and Prepare Data
```{r load-data}
# Example data
ANOVA_example<-read.table(url("https://jackauty.com/wp-content/uploads/2022/11/ANOVA_example2.txt"), header =T)
#Example data check
tab_df(head(ANOVA_example))
```
## Example plot
```{r,fig.width=6, fig.height=4}
# Define nicer colors for the groups
group_colors <- c("#1b9e77", "#d95f02", "#7570b3", "#e7298a")
ggplot(ANOVA_example, aes(x = interaction(Sex, Drug), y = Dependent, color = interaction(Sex, Drug))) +
geom_jitter(width = 0.15, size = 2) +
scale_y_continuous(expand =
expansion(mult = c(0, 0.1)),
limits = c(0, NA)) + # y starts at 0
theme_classic() + # no frame, just axes
theme(legend.position = "none") +
xlab("Sex and Drug Groups") +
ylab("Dependent Value")
```
Why I Built This RMarkdown Template
I created this RMarkdown template to produce clean, professional, and reproducible reports with minimal friction. It’s designed to be readable, portable, and easy to maintain. Here’s a breakdown of the key features and why they matter:
Structured YAML Header
The YAML section sets the foundation for a well-structured report:
- The title, author, and automatically updating date create a complete file identifier at the top.
- A table of contents (TOC) improves navigation in long documents.
- Numbered sections help with clarity and cross-referencing, especially when collaborating or publishing.
Clean, Consistent Styling with Custom CSS
A custom CSS file—pulled directly from GitHub—ensures the document is easy to read:
- Heading sizes are adjusted for hierarchy without overpowering the page.
- Code blocks have a subtle blue background and rounded corners.
- Syntax comments are styled in dark grey with smaller font to reduce visual clutter.
The result is a polished, professional look suitable for academic reports, teaching materials, or internal documentation.
Global Chunk Defaults for Focused Output
Default knitr chunk options are set to:
- Show code (transparency),
- Suppress warnings/messages (clean output),
- Disable scientific notation for readability. You will need to control how many decimal places you are desplaying. But I think it is worth it for readability.
These settings make the report easier to read while preserving all relevant information.
Smart Package Handling
A single list of packages is used throughout:
- Packages are only installed if not already present, ensuring quick setup without redundant installs.
- The same list is used for dynamic citations, reducing repetition and improving maintainability.
This makes the document highly portable—ideal for collaborative work or public-facing reproducible research.
Transparent Software Citation
All packages used are cited automatically and displayed in a clean table. This promotes good scientific practice by acknowledging the tools that power the analysis and helps others reproduce the environment accurately.
Example: Reproducible Data Loading
To demonstrate best practices, the template includes an example of loading a dataset directly from a URL. A table preview gives immediate insight into the data structure, modelling how to present data clearly and reproducibly from the start.
Example: Clean, Informative Plot
An example plot showcases how to produce publication-ready visualisations:
- Jittering reduces overplotting,
- The y-axis starts at zero to avoid misrepresentation,
- A clean theme and clear labels improve readability,
- Legends are removed when redundant.
It serves as a useful reference for creating uncluttered, effective figures.
Final Thoughts
This template is designed to:
- Produce clean and professional documents,
- Support reproducibility and collaboration,
- Keep outputs readable and focused, and
- Credit the tools used in analysis.
