Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

r - knitr: run all chunks in an Rmarkdown document

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Run all chunks is equivalent to:

  • Create a temporary R file
  • Use knitr::purl to extract all the R chunks into the temp file
  • Use source() to run the file
  • Delete the temp file

Like 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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...