This function applies a function to selected nodes of an rmd_ast or rmd_tibble.
The selection is implemented using the same approach as rmd_select() which enables
a variety of useful syntax for selecting nodes from the ast.
The function .f must return a valid rmd node object (e.g., rmd_chunk, rmd_heading, etc.).
The results are validated to ensure they maintain the proper structure and class.
Arguments
- x
Rmd object, e.g.
rmd_astorrmd_tibble.- .f
A function to apply to the selected nodes. Must return a valid rmd node object.
- ...
Selection arguments (unnamed) and function arguments (named). Unnamed arguments are used for node selection using tidyselect syntax. Named arguments are passed to the function
.f.
Value
Returns the modified Rmd object (either rmd_ast or rmd_tibble depending on input).
Only the selected nodes are modified by applying .f, while unselected nodes remain unchanged.
Examples
rmd = parse_rmd(system.file("examples/hw01.Rmd", package = "parsermd"))
# Modify specific chunks by label
f = function(node) { # Add a comment to the chunk
node@code = c("# Modified chunk", node@code)
node
}
rmd_modify(rmd, .f = f, "plot-dino") |>
rmd_select("plot-dino") |>
as_document() |>
cat(sep="\n")
#> ---
#> title: Homework 01 - Hello R
#> output: html_document
#> ---
#>
#> ```{r plot-dino}
#> #| fig-height: 3.0
#> #| fig-width: 6.0
#> # Modified chunk
#> dino_data <- datasaurus_dozen %>%
#> filter(dataset == "dino")
#>
#> ggplot(data = dino_data, mapping = aes(x = x, y = y)) +
#> geom_point()
#> ```
#>
# Modify all chunks with named arguments passed to function
f = function(node, prefix = "## ") {
node@code = paste0(prefix, node@code)
node
}
rmd_modify(rmd, f, has_type("rmd_chunk"), prefix = "# ") |>
rmd_select(has_type("rmd_chunk")) |>
as_document() |>
cat(sep="\n")
#> ---
#> title: Homework 01 - Hello R
#> output: html_document
#> ---
#>
#> ```{r load-packages}
#> #| message: false
#> # library(tidyverse)
#> # library(datasauRus)
#> ```
#>
#> ```{r plot-dino}
#> #| fig-height: 3.0
#> #| fig-width: 6.0
#> # dino_data <- datasaurus_dozen %>%
#> # filter(dataset == "dino")
#> #
#> # ggplot(data = dino_data, mapping = aes(x = x, y = y)) +
#> # geom_point()
#> ```
#>
#> ```{r cor-dino}
#> # dino_data %>%
#> # summarize(r = cor(x, y))
#> ```
#>
#> ```{r plot-star}
#> #
#> ```
#>
#> ```{r cor-star}
#> #
#> ```
#>