Reputation: 35
I'm trying to create a math test generator which randomizes which questions that are included in a test. I imagine writing 20 questions or so in knitr, and then pressing a button to create a pdf with a subset of them. I'm using R Markdown in Rstudio. I imagine a solution somewhat like:
```{r}
start<-"";end<-""
if(0<runif(1)){
start1<-"```{r, echo=F}"
end1<-"```"
}
```
`r start1`
Question 1
`r end1`
But this results in a pdf with:
```{r, echo=F}
Question 1
```
How do I tell knitr to evaluate the inline code a second time? Or is there a slicker way of doing things?
Upvotes: 3
Views: 184
Reputation: 21507
You can use cat
for that:
---
title: "Math test"
---
```{r Setup-Chunk, echo=FALSE}
q1 <- "Note down the Pythagorean theorem?"
q2 <- "Sum of angles of a triangle?"
q3 <- "What is the root of $x^2$?"
questions <- c(q1,q2,q3)
selection <- sample(length(questions), 2) # by altering 2 you pick the number of questions
```
```{r, results='asis', echo=FALSE}
out <- c()
for(i in selection){
out <- c(out, questions[i])
}
cat(paste("###", seq_along(selection), out,collapse = " \n"))
```
Visual:
Upvotes: 1