library(quarto)
# Extract R code from a Quarto document to an R script
# It will output my-analysis.R
qmd_to_r_script("my-analysis.qmd"")
This vignette demonstrates how to work with R scripts in Quarto workflows using the quarto R package. The package provides two main functions for this purpose:
qmd_to_r_script()
- Extract R code cells from Quarto documents to create R scriptsadd_spin_preamble()
- Add YAML metadata to R scripts for use with Quarto renderingThe qmd_to_r_script()
function allows you to extract R code cells from .qmd
files and convert them to .R
scripts. This is particularly useful for:
.qmd
fileslibrary(quarto)
# Extract R code from a Quarto document to an R script
# It will output my-analysis.R
qmd_to_r_script("my-analysis.qmd"")
The function preserves important metadata from your Quarto document:
#' ---
)#|
syntaxIt also have some important limitations:
Let’s create a sample Quarto document to demonstrate:
example.qmd
# Sample Quarto document content
---
title: "My Analysis"
author: "Data Scientist"
format: html
---
# Introduction
This is a sample analysis.
```{r}
#| label: setup
#| message: false
library(ggplot2)
library(dplyr)
```
```{r}
#| label: data-viz
#| fig-width: 8
#| fig-height: 6
|>
mtcars ggplot(aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth()
```
Now let’s extract the R code:
library(quarto)
# Extract R code to a script
<- qmd_to_r_script(qmd_file) r_script
Let’s see what the generated R script looks like:
example.R
#' ---
#' title: My Analysis
#' author: Data Scientist
#' format: html
#' ---
#'
#| label: setup
#| message: false
library(ggplot2)
library(dplyr)
#| label: data-viz
#| fig-width: 8
#| fig-height: 6
|>
mtcars ggplot(aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth()
When working with documents that contain multiple languages (R, Python, JavaScript, etc.), qmd_to_r_script()
will:
NULL
if no R cells are foundmixed.qmd
---
title: "Mixed Language Analysis"
format: html
---
```{r}
#| label: r-analysis
<- mtcars
data summary(data)
```
```{python}
#| label: python-analysis
import pandas as pd
= pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
df print(df.head())
```
```{ojs}
//| label: js-viz
.plot({
Plotmarks: [Plot.dot(data, {x: "x", y: "y"})]
})```
The function will inform you about the non-R cells and extract only the R code:
# Extract R code from mixed-language document
<- qmd_to_r_script(mixed_qmd)
mixed_r_script #> Extracting only R code cells from
#> 'C:\Users\chris\AppData\Local\Temp\RtmpuAG5TU\quarto-r-scripts-vignette59a8e7daf/mixed.qmd'.
#> → Other languages will be ignored (found python and ojs).
The resulting R script will contain only the R code cell:
mixed.R
#' ---
#' title: Mixed Language Analysis
#' format: html
#' ---
#'
#| label: r-analysis
<- mtcars
data summary(data)
The add_spin_preamble()
function helps you add YAML metadata to existing R scripts, making them compatible with Quarto’s script rendering feature.
# Add a simple title to an R script
add_spin_preamble("my-script.R", title = "My Analysis")
# Add custom YAML metadata
add_spin_preamble("my-script.R",
preamble = list(
title = "Advanced Analysis",
author = "Data Scientist",
format = "html",
execute = list(echo = TRUE, warning = FALSE)
))
simple.R
# Load required libraries
library(ggplot2)
library(dplyr)
# Analyze mtcars data
|>
mtcars group_by(cyl) |>
summarise(avg_mpg = mean(mpg), .groups = "drop")
# Create visualization
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot() +
labs(title = "MPG by Number of Cylinders",
x = "Cylinders", y = "Miles per Gallon")
Now add a YAML preamble:
# Add YAML metadata for Quarto rendering
add_spin_preamble(simple_script,
title = "Car Analysis",
preamble = list(
author = "R User",
format = list(
html = list(
code_fold = TRUE,
theme = "cosmo"
)
)
))#> Added spin preamble to
#> 'C:\Users\chris\AppData\Local\Temp\RtmpuAG5TU\quarto-r-scripts-vignette59a8e7daf/simple.R'.
The updated script now has YAML metadata:
simple.R
#' ---
#' author: R User
#' format:
#' html:
#' code_fold: true
#' theme: cosmo
#' title: Car Analysis
#' ---
#'
# Load required libraries
library(ggplot2)
library(dplyr)
# Analyze mtcars data
|>
mtcars group_by(cyl) |>
summarise(avg_mpg = mean(mpg), .groups = "drop")
# Create visualization
ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
geom_boxplot() +
labs(title = "MPG by Number of Cylinders",
x = "Cylinders", y = "Miles per Gallon")
This script can now be rendered with Quarto:
# Render the R script as a Quarto document
quarto_render(simple_script)
These functions work seamlessly with other quarto package functions:
# Complete workflow example
library(quarto)
# 1. Extract R code from Quarto document
<- qmd_to_r_script("analysis.qmd", output = "analysis.R")
extracted_script
# 2. Add additional metadata if needed
add_spin_preamble(extracted_script,
title = "Extracted Analysis",
preamble = list(format = "pdf"))
# 3. Render the script
quarto_render(extracted_script)
# 4. Preview the output
quarto_preview(extracted_script)
The qmd_to_r_script()
and add_spin_preamble()
functions provide a powerful toolkit for working with R scripts in Quarto workflows. Whether you’re extracting code from existing documents or preparing scripts for Quarto rendering, these functions help bridge the gap between narrative documents and standalone scripts.
For more advanced usage and additional options, see the function documentation with ?qmd_to_r_script
and ?add_spin_preamble
.