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

前端 未结 3 418
忘了有多久
忘了有多久 2021-01-03 21:40

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

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 21:54

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

提交回复
热议问题