user697473
user697473

Reputation: 2293

set chunk options on basis of chunk contents

I have an R Markdown document. Some R code chunks in this document contain calls to a function, myFun(). This function always takes a long time to run. I would therefore like to automatically set any chunks that contain myFun() to have cache = TRUE. I cannot modify myFun(), and the chunks that contain it don't have special identifying features. (For example, they don't have special labels.) Given these constraints, is it possible to automatically set cache = TRUE for chunks that contain myFun()?

The strategy that I have in mind is to create a chunk hook that searches the text of the chunk for a keyword (myFun), and that sets cache = TRUE if it finds the keyword. I don't know, though, whether this solution is feasible or whether there's a better way.

I've looked for answers in Yihui Xie's books on knitr and R Markdown, and I've searched issues at the knitr Github site. But I haven't found answers in those places. There are related posts on SO -- for example, Evaluate a Chunk based on the output format of knitr. But I haven't found anything that speaks to this problem.

Upvotes: 3

Views: 157

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30124

I tend to agree with @user2554330 that you may want to cache the function myFun() instead of code chunks (e.g., with memoise).

Anyway, to answer your question: yes, it is possible to set cache = TRUE with an option hook, e.g.,

knitr::opts_hooks$set(cache = function(options) {
  if (any(grepl('myFun(', options$code))) {
    options$cache <- TRUE
  }
  options
})

grepl() is not an entirely robust way to check if the code chunk contains a call to myFun(). If you want a most robust way, you may try utils::getParseData().

Upvotes: 3

Related Questions