Search code examples
rsweaver-exams

Is there any alternative to \Sexpr{} to write a matrix object in R?


The function \Sexpr{} does not recognize matrix object. For example, I am setting an exam question using 'exams' package in R. I have two objects generated via R commands 1. opt.obj.val 2. opt.sol. The object opt.obj.val returns scalar value while opt.sol returns matrix object. I want to use these two objects in the solution part of the question. \Sexpr{} is fine with scalar value such as opt.obj.val object. However, it does not recognize opt.sol which is a matrix object. Is it possible to use \Sexpr{} to retrieve matrix object or is there any alternative command?

<<echo=FALSE, results=hide>>=
library(lpSolve)
P1 <- c(11, 12,  10, 9)
P2 <- c(6,  7,  500,   3)
P3 <- c(8,  8.5, 7.5, 9.5)
costs <- rbind(P1, P2, P3)
row.signs <- rep("=", 3) 
row.rhs <- c(30, 30, 30) # rhs values of rows  
col.signs <- rep("=", 4)
col.rhs <- c(15, 25, 40, 10) # rhs values of columns
opt.obj.val <- lp.transport(costs, "min", row.signs, row.rhs, col.signs, col.rhs)$objval
opt.sol <- lp.transport(costs, "min", row.signs, row.rhs, col.signs, col.rhs)$solution
@

\begin{question}
a) What is the optimal objective function value?
\begin{answerlist}
  \item \Sexpr{opt.obj.val} 
  \item 780 
  \item 350 
  \item 560
  \item 710
\end{answerlist}
\end{question}

\begin{solution}
\begin{answerlist}
  \item True.
  \item False.
  \item False.
  \item False.
  \item False.
\end{answerlist}

The optimal objective function value is \Sexpr{opt.obj.val}.

The optimal solution is \Sexpr{opt.sol}.

\end{solution}

\exname{Transportation}
\extype{schoice}
\exsolution{10000}
\exshuffle{TRUE}

Solution

  • Solution: Use \Sexpr{toLatex(opt.sol)} instead of \Sexpr{opt.sol}.

    Examples: hessian and cholesky, provided within the package.

    Details:

    • The \Sexpr{x} command is mainly intended for embedding atomic vectors of length 1 into LaTeX documents. As matrices are atomic vectors (with a dim attribute), only the first element of the matrix is displayed with a warning that only the first element was selected.
    • The function toLatex() is a generic function with methods for a couple of classes of objects. The exams package provides the method for matrix objects. If you look at the output toLatex(opt.sol) you see that it returns a single character string with a straightforward {array}.
    • By default, the toLatex(x) method escapes all backslashes twice so that they can be conveniently used inside \Sexpr{}. In case the function is used outside \Sexpr{}, e.g., in an R/Markdown exercise, then toLatex(x, escape = FALSE) needs to be used.