23

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?

lucacerone
  • 9,859
  • 13
  • 52
  • 80

3 Answers3

24

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")
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • 1
    I just add to midify it slightly but it works like a champ! here is my modification: runAllChunks <- function(rmd, envir=globalenv()){ tempR <- tempfile(tmpdir = ".",fileext = ".R") knitr::purl(rmd, output=tempR) sys.source(tempR, envir=envir) unlink(tempR) } – lucacerone Jul 15 '14 at 13:33
  • @lucacerone Thank you for spotting the error in my code, and for providing your fix. I have edited the answer to reflect this. – Andrie Jul 15 '14 at 13:37
8

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().

petrelharp
  • 4,829
  • 1
  • 16
  • 17
0

load the files in raw text variable

file_name="your_file_name.Rmd"
txt <- readLines(file_name)

identify beginning and end chunk (first column will be the line where the chunks beginnings for each chunk, and second column will where the chunk ends)

chunks <- matrix(grep("```",txt),ncol =  2,byrow = T)

select all lines between beginning and end chunk which are the actual code as string

temp <- apply(chunks,1,function(x) txt[(x[1]+1):(x[2]-1)])

execute the code.(this line executes all the code codded in a string variable)

eval(parse(text = temp))