I have an .Rmd document which knitr process just fine.
I would like to run all the chunks in the document, so that I can explore the results in my R shell.
In Rstudio there is an option to run all the chunks in the document, but I can't find a way to achieve the same effect in a simple R session (opened in my terminal).
Is there a way to do this?
Run all chunks with Command + Option + R or Command + A + Enter on a Mac; Ctrl + Alt + R or Ctrl + A + Enter on Linux and Windows.
The usual way to compile an R Markdown document is to click the Knit button as shown in Figure 2.1, and the corresponding keyboard shortcut is Ctrl + Shift + K ( Cmd + Shift + K on macOS). Under the hood, RStudio calls the function rmarkdown::render() to render the document in a new R session.
knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.
Using Run all chunks
is equivalent to:
knitr::purl
to extract all the R chunks into the temp filesource()
to run the fileLike this:
tempR <- tempfile(fileext = ".R")
library(knitr)
purl("SO-tag-package-dependencies.Rmd", output=tempR)
source(tempR)
unlink(tempR)
But you will want to turn this into a function. This is easy enough, except you have to use sys.source
to run the R script in the global environment:
runAllChunks <- function(rmd, envir=globalenv()){
tempR <- tempfile(tmpdir = ".", fileext = ".R")
on.exit(unlink(tempR))
knitr::purl(rmd, output=tempR)
sys.source(tempR, envir=envir)
}
runAllChunks("SO-tag-package-dependencies.Rmd")
You don't even have to use purl()
: if you knit
the document in the R console, the code is evaluated in the global environment (by default, see the envir=
option to knit()
).
So, if your file is my.Rmd
, then just run
library(knitr)
knit('my.Rmd')
A handy trick: if you want to only run up to a certain point in the document, insert an error like:
stop('here')
at the point in a code chunk you want it to stop, and set the following knitr
option:
opts_chunk$set(error=FALSE)
in the console before running knit()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With