statquant
statquant

Reputation: 14370

How can I modify how knitr cache is stored and loaded?

when I knit a document with cache = TRUE, I often find that re-kniting is not much faster. I am wondering if the actual cached files are stored on disk in a less than optimal format and loaded back 'slowly' as well. I see in Where is knitr cached output stored? a reference to https://github.com/yihui/knitr/blob/master/R/cache.R where I think objects are stored and loaded as R data file and not stored in RAM. Questions are then:

Upvotes: 1

Views: 430

Answers (1)

user2554330
user2554330

Reputation: 44887

As shown in your link to knitr/R/cache.R, knitr sets up a list of functions to manage the cache and stores it in the unexported knitr:::cache object. That object is a list of functions; those functions share as their environment the evaluation frame from when new_cache() was called.

If you wanted to change the location where cached objects were stored, or the method used to store them, you could modify the knitr:::cache object.

This is a little tricky, because it's not an exported object. But here's how to do it:

newcache <- knitr:::cache

#  Make all the changes you like to newcache!

assignInNamespace("cache", newcache, "knitr")

For example, this document prints some info about calls to exists in the rendering log:

---
title: "Untitled"
date: "2022-07-29"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, cache = TRUE)

newcache <- knitr:::cache
oldexists <- newcache$exists
newcache$exists <- function(hash, lazy = TRUE) {
  cat("cache$exists called with hash=", hash, "\n")
  oldexists(hash, lazy)
}
assignInNamespace("cache", newcache, "knitr")
```


```{r}
x <- 1:100
print(x[1:10])
```

I saw this in the log before the usual call to Pandoc:

processing file: Untitled.Rmd
  |..................                                                    |  25%
  ordinary text without R code

  |...................................                                   |  50%
label: setup (with options) 
List of 1
 $ include: logi FALSE

  |....................................................                  |  75%
  ordinary text without R code

  |......................................................................| 100%
label: unnamed-chunk-1
cache$exists called with hash= Untitled_cache/html/unnamed-chunk-1_bc684450204aad4eef880fd842708be8 
cache$exists called with hash= Untitled_cache/html/unnamed-chunk-1_bc684450204aad4eef880fd842708be8 

Upvotes: 2

Related Questions