3

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?

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
  • 1
    personally, I'd use the following strategy: i) in a first invisible chunk, write the code for your chunks to an external R file; ii) use the code externalisation feature to evaluate those in subsequent chunks. You could probably use `knit_expand()`, but I prefer having the intermediate file. – baptiste Jan 04 '15 at 20:10

1 Answers1

1

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:
enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • Thanks for your ideas, I was unaware of the externalisation part of knitR. However, I don't get cat to accept anything like "$\lambda$" and that won't do. Reading from external R-scripts using read_chunk makes my text look like R-code as far as I can understand, I would like normal text... any thoughts on that? – Oskar Gauffin Jan 06 '15 at 12:02
  • You need to write `$\\lambda$` as "\" is a special character. See this post as reference: http://stackoverflow.com/questions/11806501/backslash-in-r-string – Rentrop Jan 06 '15 at 13:28