Knitr: Run All Chunks in an Rmarkdown Document

knitr: run all chunks in an Rmarkdown document

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

execute all R chunks at once from an Rmd document

If using Poly-Markdown+R, the command to evaluate all R snippets in an Rmarkdown document is M-n v b.

Reference

Is there a way of reformatting all code chunks in an Rmarkdown document?

The package styler can reformat Rmarkdown files.

library(styler)
style_file("badlyFormattedFile.Rmd")

It can also reformat all Rmd or R scripts in a directory using

style_dir("directoryWithUglyFiles")

R Markdown: the code chunks run, but getting errors when knitting

Instead of doing View you can just do this.

```{r}
df # assuming df is your data.frame object name
```

this will print your whole dataframe df in the knitted document.

How to evaluate all chunks in Rmarkdown

eval=TRUE is the default behaviour for .Rmd chunks, so you shouldn't need to explicitly add it to your chunks' options.

However, you do need to include {r} after your opening fences in order for the chunk to be recognised as R code and evaluated accordingly. Chunks that do not open with ```{r} will not be run, hence the problem you're seeing.

A working example might be:

```{r}
1+1
```
Some text

```{r}
2+2
```

To insert a new, empty chunk with the appropriate fences and {r}, you can press Ctrl + Alt+i on Windows, or + Option + i on Mac, or click this icon at the top right of the RStudio source pane (from memory, older versions of RStudio had an 'Insert' drop-down in that general area):

Sample Image



Related Topics



Leave a reply



Submit