qmd_to_r() extracts R code chunks from a .qmd file and writes them
to a standalone .R script using knitr::purl(). It works on any .qmd
file regardless of whether it was created with create_qmd().
Arguments
- input
A character string with the path to the
.qmdfile.- output
A character string with the path to the output
.Rfile. IfNULL(the default), the output file is written to the same directory asinputwith the.qmdextension replaced by.R.- documentation
An integer controlling how much documentation is included in the extracted script. Passed to
knitr::purl():0strips all documentation;1(the default) includes chunk labels as comments;2includes full roxygen blocks.- quiet
Logical. If
TRUE(the default), suppresses knitr's own output. toolero provides its own cli feedback instead.
Details
The parent directory of output is created if it does not already
exist, and the creation is reported. knitr::purl() does not do this
itself, so writing a derived script into R/ from a project that was
not created by init_project() would otherwise fail.
Examples
# \donttest{
# Extract R code from a qmd file
qmd <- tempfile(fileext = ".qmd")
writeLines(c(
"---",
"title: Analysis",
"---",
"",
"```{r}",
"x <- 1 + 1",
"```"
), qmd)
# Default output path: same directory, .R extension
qmd_to_r(input = qmd)
#> ✔ Extracted R code from /tmp/RtmpLziJOC/file1af613f6bb3b.qmd to /tmp/RtmpLziJOC/file1af613f6bb3b.R.
# Explicit output path. R/ is where toolero expects derived scripts;
# the directory is created if it does not exist yet.
out <- tempfile(fileext = ".R")
qmd_to_r(input = qmd, output = out)
#> ✔ Extracted R code from /tmp/RtmpLziJOC/file1af613f6bb3b.qmd to /tmp/RtmpLziJOC/file1af66cdba3f.R.
# Strip all documentation
qmd_to_r(input = qmd, output = out, documentation = 0L)
#> ✔ Extracted R code from /tmp/RtmpLziJOC/file1af613f6bb3b.qmd to /tmp/RtmpLziJOC/file1af66cdba3f.R.
# }
