Noosh
Noosh

Reputation: 687

Caching in knitr

I have multiple R chunks, so I use cache and dependson. The first chunk runs something which 3rd and 4th chunk depends on. However the 2nd chunk does some plotting from a loaded R.Data that has same variables used in 1st chunk but with different values. I tried to set cache=FALSE for 2nd chunk, and set it back to TRUE for 3rd and 4th chunk, but I get error when 3rd chunk is compiled, as some variable will be re-written when chunk 2 is compiled that is not consistent with chunk.1 I cannot put my data and code in here as it's big, but here's an example:

# first save this as a workspace 

ls <- list(vars=c("x","y","z"), data=c(1,5,6,9,5,4))
m <- mean(ls$data)
 maximum <- max(ls$data)
 ind <- which(ls$vars=="z")
 save.image("~/Desktop/test-Workspace.RData")

Then use this Rmd document

---
title: "Caching Example"

output:
  pdf_document

---

```{r chunk-1,echo=FALSE, cache=TRUE}
ls <- list(vars=c("x","y"), data=c(1,5,6,9,5,4), dens=runif(100, 0.0, 1.0))
m <- mean(ls$data)
maximum <- max(ls$data)
ind <- which(ls$vars=="z")
plot(density(ls$dens),col=2)
```

```{r chunk-2,fig.width=7.5,cache=FALSE, fig.height=7.5,echo=FALSE}
load("~/Desktop/test-Workspace.RData")
#

plot(ls$data)
print(m)
```

```{r chunk-3,echo=FALSE,dependson="chunk-1", cache=TRUE}

 plot(density(ls$dens))
 print(m)
 d<- (ls$data-m)/maximum
```

```{r chunk-4,include=FALSE,dependson=c("chunk-1","chunk-3")}
#x should be 2 again
if (length(d)!=0)
 print(d)
```

How can I do this and get no error?

Thanks!

Upvotes: 1

Views: 2494

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145785

Load your workspace into an environment. Make you second chunk something like this:

my_env = new.env()
load("test-Workspace.RData", envir = my_env)

with(my_env, plot(ls$data))
with(my_env, print(m))

And I think you won't have a problem.

Upvotes: 1

Related Questions