在以编程方式生成R降价代码时不起作用的因素

时间:2017-06-16 11:55:24

标签: r markdown

我有一些代码用于以编程方式生成数据集的直方图,因为此问题的第一个答案中的代码执行: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"))时,它会运行并生成一个列表。

1 个答案:

答案 0 :(得分:0)

出于某种原因,我不确定我的代码与this问题中代码的差异,{{nVar2}}需要在我的代码中用引号括起来。