Problems using character ' for derivatives in questions for Canvas - r-exams

I am creating differential equation questions for uploading in Canvas via zip QTI. As you may think I write something like
\[ y'' + y = x+1 \]
in the body of the question. I tested the question in a HTML display and it was ok, BUT when I build a QTI file for Canvas and upload it, the formula was not correctly displayed.
A workaround is to replace y'' with \frac{d^2y}{dx^2} which displays correctly but simply y' would be preferred.

Interestingly, the issue only occurs when using Rnw exercises but not with Rmd exercises and when using the pandoc-mathml converter (while pandoc-mathjax would work correctly, for example). It can also be replicated using exams2html() when using the following options that correspond to the setup used in Canvas:
exams2html("diffeq.Rnw", converter = "pandoc-mathml", mathjax = TRUE)
Luckily there is a simple workaround, namely in Rnw exercises use y^{''} instead of the y'' that you would use in Rmd exercises. And then make sure you use converter = "pandoc-mathml". See below for simple worked examples for the exercise files.
R/LaTeX version: diffeq.Rnw.
\begin{question}
Is this differential equation showing up correctly?
\[ y^{''} + y = x+1 \]
\begin{answerlist}
\item Yes
\item No
\end{answerlist}
\end{question}
\exname{differential equation}
\extype{schoice}
\exsolution{10}
R/Markdown version: diffeq.Rmd.
Question
========
Is this differential equation showing up correctly?
\\[ y'' + y = x+1 \\]
Questionlist
------------
* Yes
* No
Meta-information
================
exname: differential equation
extype: schoice
exsolution: 10

Related

Problem with round() function in .Rmd exercise file

I have a problem where I create a .Rmd file for an exercise and I include a large number together with the round() function. Here is a minimal example:
```{r data generation, echo = FALSE, results = "hide"}
Value = 12000.555
```
Question
========
temp
Meta-information
================
exname: temp
extype: num
exsolution: `r round(Value, 2)`
extol: 0.01
I try to compile this exercise into an exam using exams2pdf() yielding the following error:
exams2pdf("example.Rmd")
## Warning message: In read_metainfo(file) : NAs introduced by coercion
Why is that? I'm using R/exams version 2.3-6, and R version 3.6.3.
TL;DR: Use fmt(Value, 2) instead of round(Value, 2). This avoids problems with scientific notation (and uses rounding away from zero). See ?fmt for more details.
The reason for the error is actually not the round() function per se, but the fact the R by default uses scientific notation for numbers with a certain number of significant digits (factory-fresh default in R is scipen = 7). Furthermore, the knitr package (employed in the background by R/exams) tries to format this scientific notation nicely. So instead of 12000.56 the knit() function includes 1.200056 × 10<sup>4</sup> in the Markdown file. You can see this when you run xweave("example.Rmd") and then inspect the resulting example.md file. And then the subsequent processing of the exsolution tag hence has problems to convert this back to a number, hence the warning.
To avoid this you could increase the scipen limit within the R code of the exercise, e.g., options(scipen = 999). But this is very technical and tedious. This is one of the reasons why we have written the fmt(...) function that carries out various convenience tasks that have to do with formatting of numbers within R/exams exercises.

how to insert more one single-choice questions in the same exercise

I would like to use the R package 'exams' with my class and do automatic correction through scanning. For this reason, I have decided to consider only single-choice questions.
I would like to insert more than just one single-choice question in the same exercise. Apparently, this can be done only using \extype{cloze}. Is this right? I found out that only a unique begin/end pair for "question" is allowed and so is for "answerlist".
So, I have created an Rnw file whose content is:
\begin{question}
Choose between:
\begin{aswerlist}
\item a
\item b
\item c
\item d
\item e
\item f
\item a1
\item b1
\item c1
\item d1
\item e1
\item f1
\end{answerlist}
\end{question}
\begin{solution}
The right answers are:
<<echo=FALSE, results=tex>>=
soluz1 = c(1,rep(0,5))
soluz2 = c(1,rep(0,5))
soluz=c(soluz1,soluz2)
answerlist(ifelse(soluz, "True", "False"))
#
\end{solution}
%% \exname{prova}
%% \extype{cloze}
%% \exsolution{\Sexpr{mchoice2string(soluz1)}|mchoice2string(soluz2)}}
%% \exclozetype{schoice|schoice}
%% \exshuffle{5}
but I am delivered an error message:
Error in extract_environment(question, "answerlist", value = FALSE, markup = markup) :
no unique begin/end pair for‘answerlist’found
Any help would be great!
In principle, the question formatting is correct but there are two small glitches:
In the third line the code says \begin{aswerlist} instead of \begin{answerlist}. Note the missing n! This is what triggers the error message about the begin/end pairs of answerlist not matching.
The mchoice2string(soluz2) in the \exsolution{} lacks \Sexpr{} so that the code is evaluated in R.
Further comments:
In learning management systems like Moodle, such cloze exercises are easy to administer. Then using a combined cloze rather than separate schoice questions may be appealing.
However, some learning management systems (like Canvas or Blackboard) do not support cloze questions. Also, in written exams via the NOPS system schoice is easy to use but cloze is not supported.
Hence I would consider carefully which implementation strategy works better for you.
A final tip for debugging: Running xweave("myexercise.Rnw") produces a .tex file that might be useful to inspect for potential problems.

Multiple plots in repeated question yields "Error in exm[[dups[j]]] : subscript out of bounds"

When creating worksheets with exams2pdf() from R/exams, I like to repeat an exercise file multiple times to yield different numbers. However, when I include two plots in an exercise (e.g., one in the question and one in the solution) this yields:
Error in exm[[dups[j]]] : subscript out of bounds
A reproducible example is included below.
It works with one plot, and it works if I don't repeat the question. Also, the problem can be avoided by making multiple copies of a simple.Rmd (say simple1.Rmd and simple2.Rmd with different chunk names in each copy) but it seems there should be a better way.
The Rmd file: simple.Rmd
Question
========
A question.
```{r drawit}
x = (-330):330/100
y = dnorm(x)
plot(x,y)
```
Solution
========
Let's redraw...
```{r drawagain}
x2 = (-330):330/100+100
y2 = dnorm(x2,mean=100,sd=1)
plot(x2,y2)
```
Meta-information
============
extype: num
exsolution: 10
exname: calc
And the replication R code:
library("exams")
q1 = "simple.Rmd"
probs = c(q1,q1)
exams2pdf(probs)
The Rmd file will knit fine (with two plots) but running the code above yields the above mentioned
Error in exm[[dups[j]]] : subscript out of bounds
Thanks for reporting this, this is a bug in exams2pdf()! Single duplicated supplement names were already corrected but the case of multiple duplicated supplement names was not. I've just committed a fix to the repository on R-Forge that addresses the issue.
It would be great if you could install the development version of the package from R-Forge to test whether the fix also works correctly on your real use-case. You can install from within R via:
install.packages("exams", repos="http://R-Forge.R-project.org")

Can R help manuals have latex math in them?

I am working on an R package and I am using the package Roxygen2 to write the help manuals for my R functions. What I would like to know is if it is possible to use latex for math equations in the manual pages?
For example, if I had a function called add2 that did the following:
add2 = function(x,y){
z = x+y
return(z)
}
And using Roxygen2 documentation I had the following:
##' #include add2.R
{}
##' Compute the sum of x_1 and x_2
##'
##' Computes the sum of x_1 and x_2
##'
##' #param x_1 number of guys
##' #param x_2 number of girls
##' #return The sum of the two values x_1 and x_2
##'
##' #example examples/adding.R
##' #export
##' #author Name
And this works for me, but this displays x1 and x2 as x_1 and x_2 in the help manual whereas I would like for it to look like latex math and actually have the subscripts on x, i.e., $x_1$ and $x_2$ in latex.
Is there any way to do this or does R not accomodate this?
Sort of. Use something like \eqn{x_1} if you want use the (unprocessed) version of the LaTeX markup in plain-text output (alternately you could say something like \eqn{x_1}{x1}). The "sort of" part is that I'm not sure offhand for which particular output formats the LaTeX processing will be done -- for example, I'm guessing that the HTML-formatted version of output you would see in (e.g.) an RStudio documentation pane would not respect this markup. (The LaTeX markup definitely will be used in the PDF versions of the manual, which I almost never look at ...)
I'm going to go ahead and quote from the Mathematics section of Writing R Extensions ...
Mathematical formulae should be set beautifully for printed documentation yet we still want something useful for text and HTML online help. To this end, the two commands \eqn{latex}{ascii} and \deqn{latex}{ascii} are used. Whereas \eqn is used for “inline” formulae (corresponding to TeX’s $…$), \deqn gives “displayed equations” (as in LaTeX’s displaymath environment, or TeX’s $$…$$). Both arguments are treated as ‘verbatim’ text.
Both commands can also be used as \eqn{latexascii} (only one argument) which then is used for both latex and ascii. No whitespace is allowed between command and the first argument, nor between the first and second arguments.
The following example is from Poisson.Rd:
\deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%
p(x) = \lambda^x exp(-\lambda)/x!}
for \eqn{x = 0, 1, 2, \ldots}.
As of 2020-05-08, the mathjaxr package, by Wolfgang Viechtbauer, is on CRAN. It
Provides 'MathJax' and macros to enable its use within Rd files for rendering equations in the HTML help files.
From the README file:
[After installing the package, editing the package DESCRIPTION file appropriately, and adding \loadmathjax{} to the Rd file ... a]n inline equation can then be added with the \mjeqn{latex}{ascii} macro, with the LaTeX commands for the equation given between the first set of curly brackets (which will be rendered in the HTML and PDF help pages) and the plain-text version of the equation given between the second set of curly brackets (which will be shown in the plain text help). With the \mjdeqn{latex}{ascii} macro, one can add ‘displayed equations’ (as in LaTeX’s displaymath environment).
Quoting O'Reilly's "R Packages" by Hadley Wickham:
You can use standard LaTeX math (with no extensions). Choose between either inline or block display:
\eqn{a + b}: Inline equation
\deqn{a + b}: Display (block) equation
So, using \eqn and \deqn is the recommended and official way.

Documenting equations with deqn and roxygen

I'm using \deqn{}{} with roxygen2 to document equations for a function in a package. The LaTeX (the 1st argument to deqn) renders fine because white space is ignored in LaTeX equations, but I have a problem with the ASCII (the 2nd argument to deqn) representation.
The problem is that my formatting is destroyed (it appears roxygen puts the entire deqn command on a "single line" and then wraps that line at ~60 columns or so). Is there a way to force roxygen2 to preserve the white space formatting in my roxygen commands/comments in the .R file?
I have the following code in a file, example.R:
#'Example
#'
#'deqn ASCII example
#'
#'\deqn{ \sigma = \sqrt{ \frac{Z}{n} \sum
#' \left[ \textstyle\frac{1}{2}\displaystyle
#' \left( \log \frac{H_i}{L_i} \right)^2 - (2\log 2-1)
#' \left( \log \frac{C_i}{O_i} \right)^2 \right] }
#'}{sqrt(N/n * runSum(0.5 * log(OHLC[,2]/OHLC[,3])^2 -
#' (2*log(2)-1) * log(OHLC[,4]/OHLC[,1])^2, n))}
#'
#'#param x An example parameter
#'#return A example result
#'#author Joshua Ulrich
#'#keywords ts
#'#export
"example" <-
function(x) {
}
And I use the following R code to generate the example.Rd file:
library(roxygen2)
setwd("dir/containing/example.R/")
dir.create("man",FALSE)
roclet <- rd_roclet()
roc_proc(roclet, "example.R", ".")
roc_out(roclet, "example.R", ".")
You can generate the text representation of the example.Rd file using this command at the command line:
R CMD Rd2txt dir/containing/example.R/man/example.Rd
The Details section of the output from the above command looks like:
sqrt(N/n *
runSum(0.5 * log(OHLC[,2]/OHLC[,3])^2 - (2*log(2)-1) *
log(OHLC[,4]/OHLC[,1])^2, n))
whereas I would like it to look like:
sqrt(N/n * runSum(0.5 * log(OHLC[,2]/OHLC[,3])^2 -
(2*log(2)-1) * log(OHLC[,4]/OHLC[,1])^2, n))
According to Hadley Wickham, line wrapping will be removed in future versions of roxygen. So the solution for roxygen2 is to roxygenize the file (or package), then manually update the text equation in the affected .Rd file(s).
This answer doesn't address your ASCII issue, but it currently is my go-to way when rendering latex equations in HTML, so I hope this helps you.
Take a look at the mathjaxr package (CRAN, GitHub). You can install it either with install.packages("mathjaxr") or remotes::install_github("wviechtb/mathjaxr").
It introduces a macro \loadmathjax that loads the necessary JavaScript from MathJax to render latex equations. Then use the macro \mjeqn{latex}{ascii} or \mjdeqn{latex}{ascii} instead of \eqn or \deqn and you're good to go.
In your specific example, we'd have the following:
#' Example
#'
#' Example mathjax function
#'
#' \loadmathjax
#' \mjdeqn{ \sigma = \sqrt{ \frac{Z}{n} \sum
#' \textstyle\frac{1}{2}\displaystyle
#' \left\[ \left( \log \frac{H_i}{L_i} \right)^2 - (2\log 2-1) \left( \log \frac{C_i}{O_i} \right)^2 \right] }
#' }{ASCII representation}
example <- function(a, b, c) {}
(notice the open square bracket is escaped)
If you use RStudio, you may run into some trouble with the \loadmathjax macro. To preview the content quickly, do the following:
Generate documentation (Ctrl + Shift + D or devtools::document(roclets = c('rd', 'collate', 'namespace')))
Call preview_rd("example.Rd") to preview the documentation
When you're done, you can inspect the final result with these steps:
Generate documentation (Ctrl + Shift + D or devtools::document(roclets = c('rd', 'collate', 'namespace'))
Install the package (Ctrl + Shift + L or devtools::install())
Restart the R session with .rs.restartR()
Preview documentation with ?example
Either way should produce the following result:

Resources