Guy
Guy

Reputation: 318

Knitr and Parent-child R code chunks : A child's chunk can't recognize parent's variables within loop

I'm running across a problem with 'calling' a child .Rmd script within a parent code chunk. The R chunk in the parent R markdown file loops across variables, and calls a child R markdown file that uses variables from the parent.

Issue: the child markdown file will only loop through the parent's variables outside R code chunks as latex code in markdown. Anything inside an R code chunk in the child markdown file will only use the first variable in the loop. What could cause the child's latex code in markdown to work fine, but the R chunks to not follow through with the changing variables within the parent's loop?

A theoretical example of the parent file:

    ```{r setup, include=FALSE}
library(knitr)
knitr::opts_chunk$set(cache=TRUE)

x <- as.vector(list(1:10))
```
## Now for the R chunk with loop on the child
```{r parent}

xD <- NULL
for (i in 1:length(x[[1]])){
  out = NULL #reset the output of the loop to null, so duplicates aren't printed
  xD[i] <- as.numeric(x[[1]][i])*2
  currentValue <- xD[i]
  out <- c(out, knit_expand(file = "test_child.Rmd"))
  cat(knit(text=unlist(paste(out, collapse = '\n')), quiet=TRUE))
}

A theoretical example of the child file test_child.Rmd:

The value outside a code chunk is `r currentValue` and 
always updates with the variable in the parent's loop. 
```{r childchunk}
     print(paste0("But inside a code chunk, the value is", currentValue, "and
     remains the same as the first value, regardless of the parent's loop
     index.")) ```

Upvotes: 2

Views: 974

Answers (1)

Jeremy Voisey
Jeremy Voisey

Reputation: 1297

The problem is down to the use of cache = TRUE

If the chunk is cached, the code is not being executed, so the latest value of currentValue is ignored.

{r childchunk, cache = FALSE}
     print(paste0("But inside a code chunk, the value is ", currentValue, " and
     remains the same as the first value, regardless of the parent's loop
     index. Unless you set cache = FALSE")) 

Also watch out for the parent. If you leave it cached, then it won't update when you make changes just to the child. I'd suggest using

{r parent, cache = FALSE}

You could of course just use

knitr::opts_chunk$set(cache=FALSE)

Upvotes: 4

Related Questions