user210552
user210552

Reputation: 125

Sexpr is not evaluated properly in sweave?

I am trying to make a multiple choice test question using the exams package. I have created a vector of 5 questions called questions. For example, the first entry was created like:

questions[1]<-"$f(x)=\\Sexpr{a}x^2+1$"

Where a has been sampled previously.

Now I want to output the pdf file. The TeX part now reads:

 \begin{question}
*Question Statement Here*

<<echo=FALSE,results=hide, results=tex>>=
answerlist(questions)
@

\end{question}

The issue is that the output contains a instead of the numerical value representing a. However, If I manually type

answerlist(questions)

into the command line and copy paste the result in place of

 <<echo=FALSE,results=hide, results=tex>>=
    answerlist(questions)
 @

then I get the desired result.

How can I force

<<echo=FALSE,results=hide, results=tex>>=
        answerlist(questions)
        @

to output exactly what answerlist(questions) does in the command line?

Upvotes: 2

Views: 191

Answers (1)

Cedric
Cedric

Reputation: 2474

When reading into the code, answerlist just pastes values

function (..., sep = ". ", markup = c("latex", "markdown")) 
{
    if (match.arg(markup) == "latex") {
        writeLines(c("\\begin{answerlist}", paste("  \\item", 
            do.call("paste", list(..., sep = sep))), "\\end{answerlist}"))
    }
    else {
        writeLines(c("Answerlist", "----------", paste("*", do.call("paste", 
            list(..., sep = sep)))))
    }
}
<environment: namespace:exams>

From what I've tested there is nothing wrong with the following

\documentclass{exam}
\usepackage{Sweave}
\newenvironment{question}{\item \textbf{Problem}\newline}{}
\newenvironment{solution}{\textbf{Solution}\newline}{}
\begin{document}

<<init, echo=FALSE,results=hide, results=tex>>=
require(exams)
a=2;b=2
@

\begin{question}
When testing inside the R chunk I get :\\
<<test, echo=FALSE,results=hide, results=tex>>=
answerlist(a,b)
@
\newline
And this result is similar to what I get in Sexpr :\\
\Sexpr{paste(a,b,sep=". ")}
\end{question}
\end{document}

just gives

nothing wrong here

So this means that you have to give more details, I can't reproduce your problem. Note that I've tried to test with the exam package trying to understand your result using results like questions <- matrix_to_mchoice(c(2,2))$questions and this just surrounds the values with $ which is fine with the test also.

Upvotes: 1

Related Questions