2015-01-04 77 views
3

我正在尝试创建一个数学测试生成器,它随机化包含在测试中的问题。我想象在knitr中写出20个左右的问题,然后按下一个按钮来创建一个包含它们的子集的pdf。我在Rstudio中使用R Markdown。我想有点像一个解决方案:内联R代码在knitr中的第二次评估

```{r} 
start<-"";end<-"" 

if(0<runif(1)){ 
start1<-"```{r, echo=F}" 
end1<-"```" 
} 
``` 

`r start1` 
Question 1 
`r end1` 

但是,这导致PDF文件使用:

```{r, echo=F} 
Question 1 
``` 

我如何告诉knitr评估内嵌代码第二次?还是有一种轻松的做事方式?

+1

个人而言,我会使用以下策略:1)在第一不可见块,写你的块代码到外部R文件; ii)使用代码外部化功能来评估后续块。你可以使用'knit_expand()',但我更喜欢有中间文件。 – baptiste 2015-01-04 20:10:43

回答

1

您可以使用cat为:

--- 
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")) 
``` 

视觉:
enter image description here

+0

感谢您的想法,我不知道knitR的外化部分。但是,我没有让猫接受任何类似“$ \ lambda $”的东西,这是不行的。 使用read_chunk从外部R-scripts读取,使得我的文本看起来像R代码,据我所知,我想要普通文本......对此有任何想法? – 2015-01-06 12:02:17

+0

您需要编写'$ \\ lambda $',因为“\”是一个特殊字符。 看到这篇文章作为参考:http://stackoverflow.com/questions/11806501/backslash-in-r-string – Rentrop 2015-01-06 13:28:06