这在本质上与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/