【问题标题】:Avoiding repeated creation of objects in RMarkdown document through if statement通过 if 语句避免在 RMarkdown 文档中重复创建对象
【发布时间】:2015-10-29 13:27:58
【问题描述】:

我正在编写一个 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 降价创建机制来了解这些对象存在于某处并且无需再次创建它们。

【问题讨论】:

    标签: r rstudio r-markdown scoping


    【解决方案1】:

    您可能想要使用 缓存,如 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))
    }
    ```
    

    【讨论】:

      【解决方案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')
      }
      ```
      

      【讨论】:

      • 感谢您的关注。我经常使用.rds 文件。理想情况下,我不想创建很多文件,而且我在此文件中链接到网络共享,因此通过网络推送大量文件对速度没有帮助。
      • @Konrad 那么您想从控制台会话中提取当前存储在内存中的对象吗? See this question.
      • 读取已加载到全局环境的对象将是理想的解决方案。然后我可以轻松地修改它们并避免在编译文档时重新创建。缓存选项将起作用,但能够从全局环境加载将是理想的。
      • @Konrad 在我链接的帖子中,它说您可以手动编织而不是使用 rstudio,但我从未尝试过。对我来说,这种从当前 R 会话中提取变量的方法违背了创建可重现文档的目的。但也许它适合您的特定任务。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      相关资源
      最近更新 更多