Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tell if code is executed within a knitr/rmarkdown context?

Tags:

Based on some simple tests, interactive() is true when running code within rmarkdown::render() or knitr::knit2html(). That is, a simple .rmd file containing

```{r} print(interactive()) ``` 

gives an HTML file that reports TRUE.

Does anyone know of a test I can run within a code chunk that will determine whether it is being run "non-interactively", by which I mean "within knit2html() or render()"?

like image 622
Ben Bolker Avatar asked Oct 13 '15 16:10

Ben Bolker


People also ask

How do I show output in R Markdown?

If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .

How does R knitr work?

When you run render , R Markdown feeds the . Rmd file to knitr, which executes all of the code chunks and creates a new markdown (. md) document which includes the code and its output. The markdown file generated by knitr is then processed by pandoc which is responsible for creating the finished format.

How do you display output but hide code in R Markdown?

Chunk options For example, echo=FALSE indicates that the code will not be shown in the final document (though any results/output would still be displayed). You use results="hide" to hide the results/output (but here the code would still be displayed).

How can you compile the R Markdown document using knitr package?

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.


2 Answers

As Yihui suggested on github isTRUE(getOption('knitr.in.progress')) can be used to detect whether code is being knitted or executed interactively.

like image 70
CL. Avatar answered Oct 05 '22 22:10

CL.


A simple suggestion for rolling your own: see if you can access current output format:

```{r, echo = FALSE} is_inside_knitr = function() {         !is.null(knitr::opts_knit$get("out.format")) } ```  ```{r} is_inside_knitr() ``` 

There are, of course, many things you could check--and this is not the intended use of these features, so it may not be the most robust solution.

like image 25
Gregor Thomas Avatar answered Oct 06 '22 00:10

Gregor Thomas