When creating a reproducible example (reprex) in R, you often want to intersperse your code blocks with clear, readable explanations, headers, or bullet points. By default, if you use standard R comments (like # My Comment), the {reprex} package treats them as code comments and bundles everything into a single, massive R code block.

Fortunately, there is an incredibly elegant way to write native Markdown prose directly inside your R scripts. By leveraging the knitr::spin() syntax, you can tell reprex to render specific lines as markdown text rather than R comments.

The Solution: Use the #' Prefix

To write markdown text that gets rendered outside of R code blocks, simply prefix your prose lines with a hash followed by a single quote: #'. This is the standard syntax used by knitr::spin and roxygen2.

Let's look at how to structure your R script to get the exact output you want:

#' ### My Analysis
#' This is an introductory paragraph explaining the logic.
x <- 1:5 # Standard comment

#' Here is some mid-analysis commentary.
mean(x)

How the Output Renders

When you copy the code above to your clipboard and run reprex(), the package automatically parses the #' lines as standard Markdown. The resulting output will look like this:

My Analysis

This is an introductory paragraph explaining the logic.

x <- 1:5 # Standard comment

Here is some mid-analysis commentary.

mean(x)
#> [1] 3

Why This Works

Under the hood, the {reprex} package uses knitr to compile your code. knitr::spin() is a powerful feature that allows you to write a standard R script and "spin" it into an R Markdown document. Any line starting with #' is treated as R Markdown text, while everything else is treated as R code chunks. This keeps your scripts fully runnable as pure R code while still allowing rich formatting when shared on GitHub, Stack Overflow, or Slack.