Reputation: 427
I am using R Markdown to generate practice problems for a statistics class, and I like to include some randomness so that there can be multiple versions of the same problem. The students are just starting to use R themselves and I would like to be able to show the correct values in the answer R code. Basically I want to achieve something like this...
Question:
```{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"?
Answer:
To get the correct answer run the following code
```{r}
confint(reg, level = magic_function(conf))
````
where the magic_function is some function that will make the code block in the generated document look something like this...
confint(reg, level = 0.95)
Upvotes: 2
Views: 214
Reputation: 427
Thanks to user2554330 for putting me on the right path. The following gets me the desired result, although there may be a better way to do this
Answer:
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')`
UPDATE
It seems that if you want to have more than one such code chunk, you will need to use knit_child instead of knit, like so
Answer:
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')`
Upvotes: 2