我正在使用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 降价创建机制来理解我在某处存在这些对象,而无需再次创建它们。
答案 0 :(得分:2)
您可能需要使用缓存,如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))
}
```
答案 1 :(得分:2)
您可以将数据保存到.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')
}
```