|
| 1 | +--- |
| 2 | +title: "Working with R Scripts" |
| 3 | +format: |
| 4 | + html: |
| 5 | + toc: true |
| 6 | +engine: knitr |
| 7 | +vignette: > |
| 8 | + %\VignetteIndexEntry{Working with R Scripts} |
| 9 | + %\VignetteEngine{quarto::html} |
| 10 | + %\VignetteEncoding{UTF-8} |
| 11 | +--- |
| 12 | + |
| 13 | +```{r} |
| 14 | +#| label: setup |
| 15 | +#| include: false |
| 16 | +knitr::opts_chunk$set( |
| 17 | + collapse = TRUE, |
| 18 | + comment = "#>" |
| 19 | +) |
| 20 | +``` |
| 21 | + |
| 22 | +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: |
| 23 | + |
| 24 | +- `qmd_to_r_script()` - Extract R code cells from Quarto documents to create R scripts |
| 25 | +- `add_spin_preamble()` - Add YAML metadata to R scripts for use with Quarto rendering |
| 26 | + |
| 27 | +## Extracting R Code from Quarto Documents |
| 28 | + |
| 29 | +[](https://lifecycle.r-lib.org/articles/stages.html#experimental)\ |
| 30 | + |
| 31 | +The `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: |
| 32 | + |
| 33 | +- Creating standalone R scripts from Quarto documents |
| 34 | +- Sharing R code without the narrative text |
| 35 | +- Converting Quarto documents for use in environments that don't support `.qmd` files |
| 36 | + |
| 37 | +### Basic Usage |
| 38 | + |
| 39 | +```{r} |
| 40 | +#| label: basic-usage |
| 41 | +#| eval: false |
| 42 | +library(quarto) |
| 43 | +
|
| 44 | +# Extract R code from a Quarto document to an R script |
| 45 | +# It will output my-analysis.R |
| 46 | +qmd_to_r_script("my-analysis.qmd"") |
| 47 | +``` |
| 48 | + |
| 49 | +The function preserves important metadata from your Quarto document: |
| 50 | + |
| 51 | +- **YAML metadata** is converted to spin-style headers (`#' ---`) |
| 52 | +- **Chunk options** are preserved using Quarto's `#|` syntax |
| 53 | + |
| 54 | +It also have some important limitations: |
| 55 | + |
| 56 | +- **Only R code cells** are extracted; other languages (Python, Julia, etc.) are ignored |
| 57 | + |
| 58 | +### Example: Converting a Simple Quarto Document |
| 59 | + |
| 60 | +Let's create a sample Quarto document to demonstrate: |
| 61 | + |
| 62 | +```{r} |
| 63 | +#| label: create-example-qmd |
| 64 | +#| echo: false |
| 65 | +# Create a temporary directory for our examples |
| 66 | +dir.create(temp_dir <- tempfile(pattern = "quarto-r-scripts-vignette")) |
| 67 | +qmd_file <- file.path(temp_dir, "example.qmd") |
| 68 | +``` |
| 69 | + |
| 70 | +````{cat, engine.opts=list(file = qmd_file)} |
| 71 | +#| label: sample-qmd |
| 72 | +#| lang: markdown |
| 73 | +#| filename: example.qmd |
| 74 | +
|
| 75 | +# Sample Quarto document content |
| 76 | +--- |
| 77 | +title: "My Analysis" |
| 78 | +author: "Data Scientist" |
| 79 | +format: html |
| 80 | +--- |
| 81 | +
|
| 82 | +# Introduction |
| 83 | +
|
| 84 | +This is a sample analysis. |
| 85 | +
|
| 86 | +```{r} |
| 87 | +#| label: setup |
| 88 | +#| message: false |
| 89 | +library(ggplot2) |
| 90 | +library(dplyr) |
| 91 | +``` |
| 92 | +
|
| 93 | +```{r} |
| 94 | +#| label: data-viz |
| 95 | +#| fig-width: 8 |
| 96 | +#| fig-height: 6 |
| 97 | +mtcars |> |
| 98 | + ggplot(aes(x = wt, y = mpg)) + |
| 99 | + geom_point() + |
| 100 | + geom_smooth() |
| 101 | +``` |
| 102 | +```` |
| 103 | + |
| 104 | +Now let's extract the R code: |
| 105 | + |
| 106 | +```{r} |
| 107 | +#| label: extract-r-script |
| 108 | +library(quarto) |
| 109 | +
|
| 110 | +# Extract R code to a script |
| 111 | +r_script <- qmd_to_r_script(qmd_file) |
| 112 | +``` |
| 113 | + |
| 114 | +Let's see what the generated R script looks like: |
| 115 | + |
| 116 | +```{embed} |
| 117 | +#| label: r-script-output |
| 118 | +#| file: !expr r_script |
| 119 | +#| attr.source: "filename='example.R'" |
| 120 | +``` |
| 121 | + |
| 122 | +### Working with Mixed-Language Documents |
| 123 | + |
| 124 | +When working with documents that contain multiple languages (R, Python, JavaScript, etc.), `qmd_to_r_script()` will: |
| 125 | + |
| 126 | +1. Extract only the R code cells |
| 127 | +2. Provide informative messages about non-R cells |
| 128 | +3. Return `NULL` if no R cells are found |
| 129 | + |
| 130 | +```{r} |
| 131 | +#| echo: false |
| 132 | +mixed_qmd <- file.path(temp_dir, "mixed.qmd") |
| 133 | +``` |
| 134 | + |
| 135 | +````{cat, engine.opts=list(file = mixed_qmd)} |
| 136 | +#| label: mixed-qmd |
| 137 | +#| lang: markdown |
| 138 | +#| filename: mixed.qmd |
| 139 | +--- |
| 140 | +title: "Mixed Language Analysis" |
| 141 | +format: html |
| 142 | +--- |
| 143 | +
|
| 144 | +```{r} |
| 145 | +#| label: r-analysis |
| 146 | +data <- mtcars |
| 147 | +summary(data) |
| 148 | +``` |
| 149 | +
|
| 150 | +```{python} |
| 151 | +#| label: python-analysis |
| 152 | +import pandas as pd |
| 153 | +df = pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]}) |
| 154 | +print(df.head()) |
| 155 | +``` |
| 156 | +
|
| 157 | +```{ojs} |
| 158 | +//| label: js-viz |
| 159 | +Plot.plot({ |
| 160 | + marks: [Plot.dot(data, {x: "x", y: "y"})] |
| 161 | +}) |
| 162 | +``` |
| 163 | +```` |
| 164 | + |
| 165 | +The function will inform you about the non-R cells and extract only the R code: |
| 166 | +```{r} |
| 167 | +#| label: extract-mixed-r-script |
| 168 | +# Extract R code from mixed-language document |
| 169 | +mixed_r_script <- qmd_to_r_script(mixed_qmd) |
| 170 | +``` |
| 171 | + |
| 172 | +The resulting R script will contain only the R code cell: |
| 173 | + |
| 174 | +```{embed} |
| 175 | +#| label: mixed-r-script-output |
| 176 | +#| file: !expr mixed_r_script |
| 177 | +#| attr.source: "filename='mixed.R'" |
| 178 | +``` |
| 179 | + |
| 180 | +## Adding YAML Metadata to R Scripts |
| 181 | + |
| 182 | +The `add_spin_preamble()` function helps you add YAML metadata to existing R scripts, making them compatible with Quarto's script rendering feature. |
| 183 | + |
| 184 | +### Basic Usage |
| 185 | + |
| 186 | +```r |
| 187 | +# Add a simple title to an R script |
| 188 | +add_spin_preamble("my-script.R", title = "My Analysis") |
| 189 | + |
| 190 | +# Add custom YAML metadata |
| 191 | +add_spin_preamble("my-script.R", |
| 192 | + preamble = list( |
| 193 | + title = "Advanced Analysis", |
| 194 | + author = "Data Scientist", |
| 195 | + format = "html", |
| 196 | + execute = list(echo = TRUE, warning = FALSE) |
| 197 | + )) |
| 198 | +``` |
| 199 | + |
| 200 | +### Example: Preparing a Script for Quarto Rendering |
| 201 | + |
| 202 | +```{r} |
| 203 | +#| label: prepare-script |
| 204 | +#| echo: false |
| 205 | +simple_script <- file.path(temp_dir, "simple.R") |
| 206 | +``` |
| 207 | + |
| 208 | +```{cat, engine.opts=list(file = simple_script)} |
| 209 | +#| label: simple-script |
| 210 | +#| lang: r |
| 211 | +#| filename: simple.R |
| 212 | +# Load required libraries |
| 213 | +library(ggplot2) |
| 214 | +library(dplyr) |
| 215 | +
|
| 216 | +# Analyze mtcars data |
| 217 | +mtcars |> |
| 218 | + group_by(cyl) |> |
| 219 | + summarise(avg_mpg = mean(mpg), .groups = "drop") |
| 220 | +
|
| 221 | +# Create visualization |
| 222 | +ggplot(mtcars, aes(x = factor(cyl), y = mpg)) + |
| 223 | + geom_boxplot() + |
| 224 | + labs(title = "MPG by Number of Cylinders", |
| 225 | + x = "Cylinders", y = "Miles per Gallon") |
| 226 | +``` |
| 227 | + |
| 228 | +Now add a YAML preamble: |
| 229 | + |
| 230 | +```{r} |
| 231 | +#| label: add-yaml-metadata |
| 232 | +# Add YAML metadata for Quarto rendering |
| 233 | +add_spin_preamble(simple_script, |
| 234 | + title = "Car Analysis", |
| 235 | + preamble = list( |
| 236 | + author = "R User", |
| 237 | + format = list( |
| 238 | + html = list( |
| 239 | + code_fold = TRUE, |
| 240 | + theme = "cosmo" |
| 241 | + ) |
| 242 | + ) |
| 243 | + )) |
| 244 | +``` |
| 245 | + |
| 246 | +The updated script now has YAML metadata: |
| 247 | + |
| 248 | +```{embed} |
| 249 | +#| label: simple-script-with-metadata |
| 250 | +#| file: !expr simple_script |
| 251 | +#| attr.source: "filename='simple.R'" |
| 252 | +``` |
| 253 | + |
| 254 | +This script can now be rendered with Quarto: |
| 255 | + |
| 256 | +```r |
| 257 | +# Render the R script as a Quarto document |
| 258 | +quarto_render(simple_script) |
| 259 | +``` |
| 260 | + |
| 261 | +## Integration with Existing Workflows |
| 262 | + |
| 263 | +These functions work seamlessly with other quarto package functions: |
| 264 | + |
| 265 | +```r |
| 266 | +# Complete workflow example |
| 267 | +library(quarto) |
| 268 | + |
| 269 | +# 1. Extract R code from Quarto document |
| 270 | +extracted_script <- qmd_to_r_script("analysis.qmd", output = "analysis.R") |
| 271 | + |
| 272 | +# 2. Add additional metadata if needed |
| 273 | +add_spin_preamble(extracted_script, |
| 274 | + title = "Extracted Analysis", |
| 275 | + preamble = list(format = "pdf")) |
| 276 | + |
| 277 | +# 3. Render the script |
| 278 | +quarto_render(extracted_script) |
| 279 | + |
| 280 | +# 4. Preview the output |
| 281 | +quarto_preview(extracted_script) |
| 282 | +``` |
| 283 | + |
| 284 | +```{r} |
| 285 | +#| include: false |
| 286 | +#| eval: false |
| 287 | +# Clean up temporary files |
| 288 | +unlink(temp_dir, recursive = TRUE) |
| 289 | +``` |
| 290 | + |
| 291 | +## Summary |
| 292 | + |
| 293 | +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. |
| 294 | + |
| 295 | +For more advanced usage and additional options, see the function documentation with `?qmd_to_r_script` and `?add_spin_preamble`. |
0 commit comments