通过if语句避免在RMarkdown文档中重复创建对象

Avoiding repeated creation of objects in RMarkdown document through if statement

我正在处理一个 RMarkdown 文档,该文档使用需要很长时间才能创建和转换的对象。语法类似于:

---
title: "Example"
author: "Test"
date: "October 29, 2015"
output: pdf_document
---

Example

```{r}
test_exc <- "NO"
if(exists("some_dta") == FALSE) {
  set.seed(1)
  # This data is big and messy to transform and I don't want to do it twice
  some_dta <- data.frame(speed=runif(n = 1000),nonsense=runif(1000))
  test_exc <- "YES"
}
```

You can also embed plots, for example:

```{r, echo=FALSE}
plot(some_dta)
```

Was the code executed: `r test_exc`

正如上面代码中所建议的,我想避免重复执行代码 if(exists("some_dta") == FALSE) { ... }。如下面的代码所示,循环内的代码执行:

我想知道是否有一种方法可以强制 RStudio markdown 创建机制来理解我那些对象存在于某处并且不需要再次创建它们。

您可能想要使用缓存,如the online knitr documentation中所述,例如:

---
title: "Example"
author: "Test"
date: "October 29, 2015"
output: pdf_document
---

Example

```{r chunk1,cache=TRUE}
  set.seed(1)
  # This data is big and messy to transform and I don't want to do it twice
  some_dta <- data.frame(speed=runif(n = 1000),nonsense=runif(1000))
}
```

您可以将数据保存到 .rds 对象,然后 运行 检查该文件是否存在

```{r}
if(!file.exists("some_dta.rds")) {
  set.seed(1)
  # This data is big and messy to transform and I don't want to do it twice
  some_dta <- data.frame(speed=runif(n = 1000),nonsense=runif(1000))
  saveRDS(some_dta, file='some_dta.rds')
} else {
   some_dta <- readRDS('some_dta.rds')
}
```