Search code examples
rrstudior-markdownscoping

Avoiding repeated creation of objects in RMarkdown document through if statement


I'm working on a RMarkdown document that uses objects that take a long time to create and transform. The syntax is similar to this:

---
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`

As suggested in the code above I would like to avoid repeated execution of the code if(exists("some_dta") == FALSE) { ... }. As illustrated in the code below the code within the loop executes:

Markdown results

I would like to know if there is a way of forcing RStudio markdown creation mechanism to understand that I those objects exists somewhere and there is no need to create them again.


Solution

  • You might want to use caching, as described in the online knitr documentation, e.g.:

    ---
    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))
    }
    ```