knitr cache:如果数据文件改变而不是其他选项,则更新(例如,`fig.xyz`)

问题描述 投票:2回答:1

假设我使用knitr,我有一个需要一段时间才能运行的块,如果文件发生变化,我希望这个块更新但是如果我改变fig.path则不需要。后者建议我应该更改cache chunk option to 1,但后来我不能使用here建议的校验和。

以下是markdown文件的示例

---
title: "Example"
author: "Benjamin Christoffersen"
date: "September 2, 2018"
output: html_document
---

```{r setup, include=FALSE}
data_file <- "~/data.RDS"
knitr::opts_chunk$set(echo = TRUE, cache.extra = tools::md5sum(data_file))
```

```{r load_data}
dat <- readRDS(data_file)
```

```{r large_computation, cache = 1}
Sys.sleep(10)
Sys.time() # just to that result do not change
```

```{r make_some_plot}
hist(dat)
```

运行set.seed(1): saveRDS(rnorm(100), "~/data.RDS")和针织产量

enter image description here

然后运行set.seed(2): saveRDS(rnorm(100), "~/data.RDS")和针织产量

enter image description here

显示large_computation没有更新,因为cache.extra不在knitr:::cache1.opts向量中。当然,我可以保存md5sum结果,检查以前存储的文件并使用cache.rebuild或在large_computation块中执行类似的操作但是使用knitr解决方案会很好。我经常发现我改变了一些块选项(例如,dpifig.widthfig.height),因此使用cache = TRUE将无效。我想可以修改包以便能够向knitr:::cache1.opts添加选项。

r r-markdown knitr
1个回答
1
投票

如果我正确理解了这个问题,问题是如果cache.extra设置为cache,则不考虑1。事实上,this is by design

如果外部文件(或更一般的:提供给cache = 1的某个值)发生更改,则所需的行为是使所有块的缓存(包括使用cache.extra的块)无效。

正如问题所述,实现这一目标的一种方法是使用chunk option cache.rebuild,但不是手动跟踪外部文件的变化,如果knitr的内置缓存功能,我会利用:

```{r cachecontrol, cache = TRUE, cache.extra = tools::md5sum(data_file)}
knitr::opts_chunk$set(cache.rebuild = TRUE)
```

将此作为早期块添加,如果data_file发生更改,则所有后续块的缓存都将失效。我们的想法是缓存控制后续块缓存的块 - 但前提是外部文件不变。

当然,只有在评估cachecontrol块之前没有更改全局块选项时,这才有效。


问题的完整示例:

用不同的种子运行set.seed(1); saveRDS(rnorm(100), "data.RDS")来生成不同的外部文件,然后编织:

---
title: "Invalidate all chunks condidional on external file (even if cache=1)"
output: html_document
---

```{r}
data_file <- "data.RDS"
```

```{r cachecontrol, include = FALSE, cache = TRUE, cache.extra = tools::md5sum(data_file)}
# do NOT change global chunk options before this chunk
knitr::opts_chunk$set(cache.rebuild = TRUE)
```

```{r setup, include = FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.width = 8)
```


```{r load_data}
dat <- readRDS(data_file)
```

```{r large_computation, cache = 1}
Sys.sleep(10)
Sys.time() # just to show that result do not change unless external file changes
```

```{r make_some_plot}
hist(dat)
```
© www.soinside.com 2019 - 2024. All rights reserved.