From RStudio, is it possible to knit only part of an R Markdown document?

You can achieve what you want in many ways:

  • use the R notebooks, instead than the R Markdown document, as suggested above by @mara:
  • use @DavoWW knitr::knit_exit() trick: knit_exit() doesn't simply abort knitting. It just stops it at the point where you placed it. So you get an HTML file as an output, but of course without the parts you didn't knit (which is probably not good for your use case).

  • concerning caching options, invert your point of view :grinning: instead than going chunk by chunk, just set the default (e.g., cache all chunks) with opts_chunk$set(...) at the beginning of your doc, and then deactivate caching only in the chunk you're currently editing, for example

  • move the analysis-heavy part of the code outside the R Markdown document completely to an R script (it also makes debugging easier). The script must save the results of the analysis to some file, e.g., .csv, .rds, .rda or a feather file. Then in the R Markdown you can add a chunk with an if statement, which checks if the file exists (in which case it loads it) otherwise it sources the analysis script. This way, knitting takes way less time.

  • use drake! It requires changing your mindset quite a bit, so it definitely isn't an easy step. The reward is that it accelerates quite a lot the process of developing and reproducing time-consuming analyses.

6 Likes