1

I've got some code with is meant to programmatically generate histograms of a dataset, as the code in the first answer to this question does: R knitr: Possible to programmatically modify chunk labels?.

My code template is:

```{r, results='asis'}
cat("### {{nVar2}} categories")
```

```{r}
hist(df1$Var1[df1$Var2 == {{nVar2}}])
```

which is saved as 'template.Rmd'.

My markdown output code is:

```{r}
df1 <- data.frame(Var1 = c(0.4,0.3,0.6,1,0,0.1,0.3,0.8,0.2,0.9,0.8,1,1,0.5,0.2,0.6,0.3,0.4,0.1,0.6,0.9,0.9,0.9,0))
df1$Var2[df1$Var1 <= 1] <- "D"
df1$Var2[df1$Var1 <= 0.75] <- "C"
df1$Var2[df1$Var1 <= 0.5] <- "B"
df1$Var2[df1$Var1 <= 0.25] <- "A"
Var2.levels <- unique(df1$Var2)
```

```{r, include=FALSE}
library(knitr)
src <- lapply(Var2.levels, function(nVar2) knit_expand(file = "template.Rmd"))
```

`r knit(text = unlist(src))`

When I run it I get the following error

Error in hist(df1$Var1[df1$Var2 == B]) : object 'B' not found Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> hist

Weirdly though, when I remove the code chunk below, so that it only outputs each of the levels of Var2 with 'categories' it works fine:

```{r}
hist(df1$Var1[df1$Var2 == {{nVar2}}])
```

Also, when I run just src <- lapply(Var2.levels, function(nVar2) knit_expand(file = "template.Rmd")) it runs and produces a list.

tktk234
  • 426
  • 3
  • 12

1 Answers1

0

For some reason, and I'm not sure of the descrepancy from my code to the code in this question, the {{nVar2}} needs to be enclosed in quotes in my code.

tktk234
  • 426
  • 3
  • 12