如何使用 R 考试在 Rnw 文件中进行评论

How to comment inside a Rnw file with R exams

我想知道是否可以在 Rnw 文件练习中添加注释,以便 R 和 LaTeX 可以完全忽略某些内容。这对我进行一些灵活性建设练习很有用。

特别是,我想做一个有五个选项的多项选择题,给出两个正确的陈述和两个错误的陈述,并在一个正确的陈述和两个错误的陈述之间随机选择另一个陈述。尝试像 http://www.r-exams.org/templates/boxplots/ 那样实现这一点对我来说非常困难,因为所有这些语句都涉及 LaTeX 编码,所以我在将它插入 R chunck 时遇到了问题。所以我尝试了一些不同的方法,但我收到一条错误消息,指出解决方案和问题列表的长度不匹配。也许,有一些方法可以使评论有效。

<<echo=FALSE, results=hide>>=

scelta=sample(c("%'","%'",""),size=3, replace=FALSE)
if (scelta[1]=="%'") soluz=c(1,1,rep(0,3)) else soluz=c(1,1,1,0,0)

@

\begin{question}

Say which statements are true. 

\begin{answerlist}

 \item first true statement
\item second true statement
\Sexpr{scelta[1]} \item third true statement 

\item first wrong statment
\item second wrong statment 
\Sexpr{scelta[2]} \item statment
\Sexpr{scelta[3]} \item statement

\end{answerlist}
\end{question}


\begin{solution}

<<echo=FALSE, results=tex>>=
answerlist(ifelse(soluz, "Vero", "Falso"))
@

\end{solution}


\exname{name_exercise}
\extype{mchoice}
\exsolution{\Sexpr{mchoice2string(soluz)}}
\exshuffle{5} 

所以,可能我遇到困难是因为我对 Sweave 不够熟悉,但我的问题也许可以通过 R/exams 以多种方式解决。任何帮助将不胜感激。

我刚刚找到了让它工作的方法。基本上,我了解到我可以使用四重反斜杠进行转义。所以,在这一点上,我也可以像在箱线图示例中那样做。 仍然欢迎任何评论或建议。

<<echo=FALSE, results=hide>>=

scelta=sample(c("%","%","\\item"),size=3, replace=FALSE)
if (scelta[1]=="%") soluz=c(1,1,rep(0,3)) else soluz=c(1,1,1,0,0)

@

\begin{question}

Say which statements are true. 

\begin{answerlist}

 \item first true statement
\item second true statement
\Sexpr{scelta[1]} third true statement 

\item first wrong statment
\item second wrong statment 
\Sexpr{scelta[2]} third wrong statment
\Sexpr{scelta[3]} fourth wrong statement

\end{answerlist}
\end{question}


\begin{solution}

<<echo=FALSE, results=tex>>=
answerlist(ifelse(soluz, "Vero", "Falso"))
@

\end{solution}


\exname{name_exercise}
\extype{mchoice}
\exsolution{\Sexpr{mchoice2string(soluz)}}
\exshuffle{5} 

我不建议通过插入注释来执行此操作,因为 (a) 代码(至少在我看来)不太清楚,并且 (b) 您受限于某些采样模式。相反,我宁愿在 R 代码中做这样的事情:

ans <- c(
  "This is the first statement and correct.",
  "This is the second statement and also correct.",
  "This is the third and last correct statement.",
  "This is the fourth statement and it is false.",
  "This is the fifth statement, the second false one.",
  "This is the sixth statement, false again.",
  "This is the seventh statement, it is false and the last one."
)
sol <- rep(c(TRUE, FALSE), c(3, 4))
i <- sample(1:7, 5)
ans <- ans[i]
sol <- sol[i]

这设置了所有答案和所有解决方案以及样本,没有任何限制,七个答案中的五个以及相应的解决方案。然后,您可以使用 answerlist(ans) 等将答案列表包含在问题中。

然后通过替换 i 的计算方式,很容易切换到任何其他形式的采样。例如,您可以这样做:

i <- c(sample(1:3, 2), sample(4:7, 2)) ## two true, two false
i <- sample(setdiff(1:7, i), 1)        ## one additional
i <- sample(i)                         ## permute

由于最后一行,也不需要设置 exshuffle 标签。