Ben Bolker
Ben Bolker

Reputation: 226027

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

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

Upvotes: 28

Views: 2637

Answers (3)

Gregor Thomas
Gregor Thomas

Reputation: 145745

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.

Upvotes: 6

CL.
CL.

Reputation: 14957

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

Upvotes: 45

Josh O'Brien
Josh O'Brien

Reputation: 162311

I suspect (?) you might just need to roll your own.

If so, here's one approach which seems to perform just fine. It works by extracting the names of all of the functions in the call stack, and then checks whether any of them are named "knit2html" or "render". (Depending on how robust you need this to be, you could do some additional checking to make sure that these are really the functions in the knitr and rmarkdown packages, but the general idea would still be the same.)

```{r, echo=FALSE}
isNonInteractive <- function() {
    ff <- sapply(sys.calls(), function(f) as.character(f[[1]]))
    any(ff %in% c("knit2html", "render"))
}
```

```{r}
print(isNonInteractive())
```

Upvotes: 3

Related Questions