Second evaluation of inline R code in knitr
I am trying to create a math test generator that randomizes which questions are included in a test. I imagine 20 questions or so in knitr and then click a button to create a PDF with a subset of them. I am using R Markdown in Rstudio. I imagine the same solution as:
```{r}
start<-"";end<-""
if(0<runif(1)){
start1<-"```{r, echo=F}"
end1<-"```"
}
```
`r start1`
Question 1
`r end1`
But this leads to the fact that with:
```{r, echo=F}
Question 1
```
How do I tell knitr to evaluate inline code a second time? Or is there a smoother way to do things?
+3
source to share
1 answer
You can use cat
for this:
---
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:
+1
source to share