r - 为什么knitr缓存的data.table`:=`失败?

标签 r caching data.table knitr

这在本质上与this问题有关,但是在机制上必须有所不同。

如果尝试缓存包含knitr data.table分配的:=块,则它的作用就好像该块尚未运行,以后的块看不到:=的影响。

知道为什么会这样吗? knitr如何检测对象已更新,并且data.table这样做会引起混淆吗?

看来您可以通过执行DT = DT[, LHS:=RHS]来解决此问题。

例:

```{r}
library(data.table)
```
Data.Table Markdown
========================================================
Suppose we make a `data.table` in **R Markdown**
```{r, cache=TRUE}
DT = data.table(a = rnorm(10))
```
Then add a column using `:=`
```{r, cache=TRUE}
DT[, c:=5] 
```
Then we display that in a non-cached block
```{r, cache=FALSE}
DT
```
The first time you run this, the above will show a `c` column, 
from the second time onwards it will not.


第二次运行时输出

最佳答案

推测:

这似乎正在发生。

knitr在创建对象后就非常明智地缓存它们。然后,只要检测到缓存值已被更改,它就会更新它们的缓存值。

但是,data.table绕过R的常规按值分配和替换机制,并使用:=运算符而不是=<<-<-。结果,knitr无法接收到DT已被DT[, c:=5]更改的信号。

解:

只要将此块添加到您的代码中,只要您想重新缓存DT的当前值即可。它不会花费您任何内存或时间(因为除了DT <- DT复制了引用以外,什么也没有),但是它确实向knitr发送了一个(伪)信号,表明DT已被更新:

```{r, cache=TRUE, echo=FALSE}
DT <- DT 
```




示例文档的工作版本:

通过运行此编辑后的文档版本来检查其是否有效:

```{r}
library(data.table)
```
Data.Table Markdown
========================================================
Suppose we make a `data.table` in **R Markdown**
```{r, cache=TRUE}
DT = data.table(a = rnorm(10))
```

Then add a column using `:=`
```{r, cache=TRUE}
DT[, c:=5] 
```

```{r, cache=TRUE, echo=FALSE}
DT <- DT 
```

Then we display that in a non-cached block
```{r, cache=FALSE}
DT
```
The first time you run this, the above will show a `c` column. 
The second, third, and nth times, it will as well.

关于r - 为什么knitr缓存的data.table`:=`失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15298359/

相关文章:

r - 在 R 中跳过 read.csv 中的一些行

r - 通过创建唯一列复制行

caching - Redis 在填满和逐出键时有多慢? (LRU算法)

caching - 在构建之间使用 gitlab ci runner 时如何为 sbt 启用 .ivy2 缓存

r - 按行计算超过数据框中值的列数

r - Fisher 在 R 中根据数据帧进行精确测试

r - 如何从表格中使用 R 制作条形图?

r - 基于多个列计算排名,具有优先规则

r - 在 data.table 的 i 中使用匹配