内联 R 表达式 returns 不正确的值

In-line R expression returns incorrect value

如果 Rmd 文件中的 R 代码重复使用相同的变量名,则内联 r 表达式似乎 return 此变量的最后一个值,而不管内联表达式的位置如何。除了确保在文档的不同部分不重复使用相同的变量名之外,是否可以避免这种行为?

可重现的例子

---
title: "R Notebook"
output: html_notebook
---


```{r}
df <- cars
nrow(df)
```

The dataset has `r nrow(df)` rows.


```{r}
df <- iris
nrow(df)
```

The dataset has `r nrow(df)` rows.

这会产生以下输出

我正在使用: R 版本 3.3.2 (2016-10-31) 平台:x86_64-w64-mingw32/x64(64 位) 运行 下:Windows 7 x64(内部版本 7601)Service Pack 1

rmarkdown_1.4 knitr_1.15.1

开头我们可以指定cache = TRUE

---
title: "R Notebook"

output: 
html_notebook: default


---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(cache=TRUE)
```


```{r}
df <- cars
nrow(df)
```

问题是,在您的 header 中,您是 "previewing" 您的文件,实际上 运行 您的代码并不是从头开始的。你必须把它编织成 HTML 才能得到它 运行 这样你的 in-line 代码就正确了。

问题Header

---
title: "R Notebook"
output: html_notebook
---

解决方案Header

---
title: "R Notebook"
output: 
    html_document: default
    html_notebook: default
---

其他注意事项

之前的解决方案有两个问题。首先,从 RMarkdown 文档中,"Inline expressions do not take knitr options"(参见 http://rmarkdown.rstudio.com/lesson-4.html 的末尾)

其次,之前答案的 YAML 格式不正确,迫使 RStudio 实际编织文件。正确的格式会产生与您遇到的相同的问题

---
title: "R Notebook"
output: 
    html_notebook: default
---