我正在使用R Markdown生成统计类的练习题,并且我希望包括一些随机性,以便同一问题可以有多个版本。学生们才开始自己使用R,我希望能够在答案R代码中显示正确的值。基本上我想实现这样的目标...
问题:
```{r, include=FALSE}
conf <- sample(c(0.9,0.95,0.99), 1)
```
What is the `r conf * 100`% confidence interval for the slope coefficient of your regression "reg"?
答案:
To get the correct answer run the following code
```{r}
confint(reg, level = magic_function(conf))
````
其中magic_function是一些函数,它将使生成的文档中的代码块看起来像这样……
confint(reg, level = 0.95)
答案 0 :(得分:2)
感谢user2554330将我带入正确的道路。尽管可能有更好的方法,但以下方法使我获得了期望的结果
答案:
To get the correct answer run the following code
```{r, include=FALSE}
code <- c("```{r}", knit::knit_expand(text = "confint(reg_result, level = {{conf}})", conf = conf), "```")
```
`r paste(knitr::knit(text = code), collapse = '\n')`
更新
似乎,如果您想拥有多个这样的代码块,则需要使用knit_child而不是knit,就像这样
答案:
To get the correct answer run the following code
```{r, include=FALSE}
code <- c("```{r}", knit::knit_expand(text = "confint(reg_result, level = {{conf}})", conf = conf), "```")
```
`r paste(knitr::knit_child(text = code), collapse = '\n')`