推测:
这就是正在发生的事情。
knitr一旦对象被创建,就相当明智地缓存它们。然后,每当它检测到它们已被更改时,它就会更新它们的缓存值。
数据表不过,它绕过了 R 正常的按值复制赋值和替换机制,并使用:=
运算符而不是=
, <<-
, or <-
。因此knitr没有收到以下信号DT
已更改为DT[, c:=5]
.
解决方案:
只需将此块添加到您的代码中任何您想要当前值的位置DT
重新缓存。它不会花费你任何内存或时间(因为除了引用之外没有任何东西被复制)DT <- DT
)但它确实有效地发送了一个(假)信号knitr that 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.