我有一些代码用于以编程方式生成数据集的直方图,因为此问题的第一个答案中的代码执行:R knitr: Possible to programmatically modify chunk labels?。
我的代码模板是:
```{r, results='asis'}
cat("### {{nVar2}} categories")
```
```{r}
hist(df1$Var1[df1$Var2 == {{nVar2}}])
```
保存为'template.Rmd'。
我的降价输出代码是:
```{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))`
当我运行它时,我收到以下错误
Error in hist(df1$Var1[df1$Var2 == B]) : object 'B' not found Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> hist
奇怪的是,当我删除下面的代码块时,它只输出Var2的每个级别和'categories'它可以正常工作:
```{r}
hist(df1$Var1[df1$Var2 == {{nVar2}}])
```
此外,当我只运行src <- lapply(Var2.levels, function(nVar2) knit_expand(file = "template.Rmd"))
时,它会运行并生成一个列表。