Search code examples
rr-markdownknitrquarto

Extract `setup` code chunk from `.qmd` file and execute (source) it


I am looking for a way to extract a code block / chunk named setup from a .qmd file and execute the code block (effectively sourcing it, I assume).

Is there a way of achieving this?

I am using rmarkdown::yaml_front_matter()$params to get the parameter, but looking into other functions in the knits package did not help.


Solution

  • Supposing you have foo.qmd like this:

    ---
    output: revealjs
    ---
    
    ```{r setup}
    library(tidyr)
    library(stringr)
    ```
    
    ```{r}
    iris
    ```
    

    You can use parsermd to parse the file and extract the item you want (code chunks, headings, etc.). Then, remove the elements from the markdown syntax and evaluate the code:

    library(parsermd)
      
    rmd <- parse_rmd("foo.qmd")
      
    setup_chunk <- rmd_select(rmd, "setup") |> 
      as_document()
    
    setup_chunk <- setup_chunk[-grep("```", setup_chunk)]
    setup_chunk
    #> [1] "library(tidyr)"   "library(stringr)" ""                
    
    eval(parse(text = setup_chunk))             
    

    An alternative is to write setup_chunk to a file and source() it.