为什么knitr缓存失败data.table`:=`? [英] why does knitr caching fail for data.table `:=`?
问题描述
这在精神上与此问题有关,但在机制上必须有所不同。
This is related in spirit to this question, but must be different in mechanism.
如果您尝试缓存包含 data.table
<$>的 knitr
c $ c>:= assignement,那么它的行为好像该块尚未运行,后来的块没有看到:=
。
If you try to cache a knitr
chunk that contains a data.table
:=
assignement then it acts as though that chunk has not been run, and later chunks do not see the affect of the :=
.
任何想法为什么会是这样? knitr
如何检测对象已更新,什么是 data.table
这样做会导致混淆?
Any idea why this is? How does knitr
detect objects have updated, and what is data.table
doing that confuses it?
看来你可以通过 DT = DT [,LHS:= RHS]
来解决这个问题。
It appears you can work around this by doing DT = DT[, LHS:=RHS]
.
:
Example:
```{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.
第二次投放时输出
推荐答案
猜测:
这是看上去正在发生的事。
Speculation:
Here is what appears to be going on.
strong> knitr 相当明智地缓存对象,只要它们被创建。然后,当它检测到它们已经被改变时,它更新它们的缓存值。
knitr quite sensibly caches objects as as soon as they are created. It then updates their cached value whenever it detects that they have been altered.
data.table 虽然绕过了R的正常的按值分配和替换机制,并使用 :=
运算符,而不是 =
,< < -
c $ c>< - 。因此, knitr 未收到 DT
已被 DT [,c:= 5]更改的信号]
。
data.table, though, bypasses R's normal copy-by-value assignment and replacement mechanisms, and uses a :=
operator rather than a =
, <<-
, or <-
. As a result knitr isn't picking up the signals that DT
has been changed by DT[, c:=5]
.
只需将此块添加到您的代码'd喜欢 DT
的当前值被重新缓存。它不会花你任何内存或时间(因为除了引用被复制 DT < - DT
),但它有效地发送一个(假的)信号到 knitr , DT
已更新:
Just add this block to your code wherever you'd like the current value of DT
to be re-cached. It won't cost you anything memory or time-wise (since nothing except a reference is copied by DT <- DT
) but it does effectively send a (fake) signal to knitr that DT
has been updated:
```{r, cache=TRUE, echo=FALSE}
DT <- DT
```
示例doc的工作版本:
您的文档的已修改版本:
Working version of example doc:
Check that it works by running this edited version of your doc:
```{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.
这篇关于为什么knitr缓存失败data.table`:=`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!