knitr中内联R代码的二次求值
我正在尝试创建一个数学测试生成器,它可以随机化测试中包含的问题。我想象用knitr写20个左右的问题,然后按下一个按钮创建一个包含其中一部分的pdf。我在Rstudio中使用R标记。我设想的解决方案有点像:knitr中内联R代码的二次求值,r,knitr,R,Knitr,我正在尝试创建一个数学测试生成器,它可以随机化测试中包含的问题。我想象用knitr写20个左右的问题,然后按下一个按钮创建一个包含其中一部分的pdf。我在Rstudio中使用R标记。我设想的解决方案有点像: ```{r} start<-"";end<-"" if(0<runif(1)){ start1<-"```{r, echo=F}" end1<-"```" } ``` `r start1` Question 1 `r end1` 我如何告诉knitr再次
```{r}
start<-"";end<-""
if(0<runif(1)){
start1<-"```{r, echo=F}"
end1<-"```"
}
```
`r start1`
Question 1
`r end1`
我如何告诉knitr再次计算内联代码?或者有更巧妙的方法吗?您可以使用
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"))
```
---
标题:“数学考试”
---
```{r安装程序块,echo=FALSE}
就个人而言,我会使用以下策略:I)在第一个不可见块中,将块的代码写入外部R文件;ii)使用代码外部化功能来评估后续块中的代码。您可能可以使用knit_expand()
,但我更喜欢中间文件。感谢您的想法,我不知道knitR的外部化部分。但是,我不会让cat接受像“$\lambda$”这样的内容,这是不行的。使用read_chunk从外部R脚本读取使我的文本看起来像R代码,就我所能理解的而言,我想要普通文本。。。有什么想法吗?你需要写$\\lambda$
,因为“\”是一个特殊字符。请参阅此帖子作为参考:
---
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"))
```