Rmarkdown to Epub - how to get latex to show up? - r

I've been writing some documents with Knitr and Rmarkdown to .pdf, but it turns out I need to have then in .epub format instead.
I had been running a command like this to convert the .md files to .epub.
pandoc --mathjax -s --highlight-style tango file.md --to epub -o output.epub
That seems to have some issue handling latex code, though. Inline latex code with $x_1$, for example, seems to work fine. However, for latex blocks like:
$$
x_1 = 1, x_2 = 1 \\
h(x) = f(-20 + 15 + 17) \\
h(x) = f(12) \approx 1 \\
$$
It just displays the raw latex:
\[ x\_1 = 1, x\_2 = 1 \\\\ h(x) = f(-20 + 15 + 17) \\\\ h(x) = f(12) \\approx 1 \\\\ \]
Am I using latex for multi-line equations wrong in Rmarkdown? Is there a recommended way to get big chunks of latex working with Epub?

From Creating an ebook with pandoc
:
Pandoc has an EPUB3 writer. It renders LaTeX math into MathML, which EPUB3 readers are supposed to support (but unfortunately few do). Use pandoc -t epub3 to force EPUB3 output, as opposed to EPUB2 which is the default.
Of course, this isn't much help if you want EPUB2 output or target readers that don't support MathML. Then you should try using the --webtex option, which will use a web service to convert the TeX to an image.

Though I can't really reproduce your issue (at least the line breaks are discarded) -- eventually it's worth to use some more latex code for your equation:
\begin{equation}
\begin{aligned}
\label{eq7}
x_1 = 1, x_2 = 1 \\
h(x) = f(-20 + 15 + 17) \\
h(x) = f(12) \approx 1 \\
\end{aligned}
\end{equation}

Related

"missing { inserted" in latex equation mode

I am writing an equation in latex.
\begin{equation}
\label{eq:beta}
\beta_{ji}=softmax(w{_b^T}tanh(W_3v{_j^'}+W{_4q^'}))
\end{equation}
But the equation number is not displaying at the right side, also the latex giving me an error
missing { inserted
my equation is displayed here
what could be the possible reason
In LaTeX, you need to specify inside curly brackets separately what string is the subscript and what string is the superscript. Here there are three examples of how this influences the output result:
\begin{equation}
\label{eq:beta}
\beta_{ji} = softmax( w_{b}^{T} tanh (W_{3} v_{j}^{'} + W_{4q}^{'}) )
\end{equation}
\begin{equation}
\label{eq:beta}
\beta_{ji} = softmax( {w_{b}}^{T} tanh (W_{3} v_{j^{'}} + W_{4q^{'}}) )
\end{equation}
\begin{equation}
\label{eq:beta}
\beta_{ji} = softmax( {w^{T}}_{b} tanh (W_{3v_{j^{'}}} + {W^{'}}_{4q}) )
\end{equation}

Rmarkdown not building model equation to word

This is my code for linear model
model = lm(UCBRpk~ pksa + dist)
summary(model)
equatiomatic::extract_eq(model,wrap = TRUE)
equatiomatic::extract_eq(model, wrap = TRUE,use_coefs = TRUE)
I got the equation when knitting to html and pdf, but unable in word
This is the usual error message each time I knit to word:
unexpected "&"
expecting "%", "\\label", "\\nonumber" or whitespace
[WARNING] Could not convert TeX math '
\begin{aligned}
\operatorname{\widehat{SCBRcp}} &= 43.34 + 3.53(\operatorname{cpa}_{\operatorname{10\%}}) + 2.68(\operatorname{cpa}_{\operatorname{2\%}}) + 4.67(\operatorname{cpa}_{\operatorname{4\%}})\ + \\
&\quad 8.9(\operatorname{cpa}_{\operatorname{6\%}}) + 6.24(\operatorname{cpa}_{\operatorname{8\%}}) + 3.15(\operatorname{dist}_{\operatorname{A2}}) - 1.81(\operatorname{dist}_{\operatorname{A3}})
\end{aligned}
', rendering as TeX:
d}
tldr;
Seems like a bug with equatiomatic; I recommend opening an issue.
The issue is with the \operatorname calls in the LaTeX code produced by equatiomatic. I don't know whether the culprit is MathJax (since the expression itself is valid LaTeX) but a more minimal example reproducing your issue is as follows:
---
title: "Untitled"
output: word_document
---
$$
\begin{aligned}
\operatorname{\widehat{x}} &= a + b\ + \\
&\quad c + d
\end{aligned}
$$
which upon knitting produces the following warning
[WARNING] Could not convert TeX math '
\begin{aligned}
\operatorname{\widehat{x}} &= a + b\ + \\
&\quad c + d
\end{aligned}
', rendering as TeX:
ligned}
^
unexpected "&"
expecting "%", "\\label", "\\nonumber" or whitespace
I am not familiar with equatiomatic but in my (LaTeX) opinion, the translation of those equations into LaTeX should use \mathrm rather than \operatorname (see e.g. What's the difference between \mathrm and \operatorname? for a discussion and examples on how these two differ; amongst other things, \operatorname treats punctuation symbols like text whereas \mathrm treats them as math symbols. Perhaps -- and I'm 100% speculating here -- that's the reason why the equatiomatic devs decided to use \operatorname rather than \mathrm).
If I replace all \operatorname calls with \mathrm your example expression compiles fine.
---
title: "Untitled"
output: word_document
---
$$
\begin{aligned}
\mathrm{\widehat{SCBRcp}} &= 43.34 + 3.53(\mathrm{cpa}_{\mathrm{10\%}}) + 2.68(\mathrm{cpa}_{\mathrm{2\%}}) + 4.67(\mathrm{cpa}_{\mathrm{4\%}})\ + \\
&\quad 8.9(\mathrm{cpa}_{\mathrm{6\%}}) + 6.24(\mathrm{cpa}_{\mathrm{8\%}}) + 3.15(\mathrm{dist}_{\mathrm{A2}}) - 1.81(\mathrm{dist}_{\mathrm{A3}})
\end{aligned}
$$
So long story short, what can you do? Other than manually editing the output of equatiomatic I recommend opening an issue on the equatiomatic GH site, and cross-linking to this post on Stack Overflow.

Breaking a long equation up into two lines in R Markdown

I am using R Markdown using the texevier package
I have a long equation which I would like to seperate into two lines by seperating with a linebreak operator "\\". Here is the code chunk that I'm trying to run
\begin{equation}
l = -0.5 \sum_{t=1}^{T}[n log(2\pi) + log(\mid H_t \mid) + \varepsilon_t^{'} H_t \varepsilon_t] \\ = -0.5 \sum_{t=1}^{T}[n log(2\pi) + log(\mid D_t R_t D_t \mid) + \upsilon_t^{'}D_t^{-1}R_t^{-1}D_t^{-1}\upsilon_t]
\label{eq5}
\end{equation}
However, it seems that this does not make the contents after the seperator start on a seperate line. Does anyone have advice on how I should go about doing this?

Equation trouble in Rmarkdown

Keep getting a message:
! Missing { inserted.
<to be read again>
\left
l.70 \end{frame}
when running the R markdown file below (in RStudio). I have spent a few hours pulling my hair out trying to figure out why? The equation renders in the preview.
---
title: "Compile Please"
output: beamer_presentation
---
## This Equation is Poison for Rmd
$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right) ^ \left( x \right) $$
It may be picky about spaces there. This "tighter" version with explicit parens to protect that exponentiated works here:
$$ f(x) = \left( 1 + \frac{x}{m - \alpha} \right)^{\left( x \right)} $$

How to use R package exams with portuguese accents?

When I'm using the package exams to generate questions, I can do it perfectly in english even with special characters. For example, a Rnw question that I can compile with exams package:
<<echo=FALSE, results=hide>>=
## DATA GENERATION
P <- round(runif(n = 1, min = 1000, max = 2000), digits = 2)
S <- round(runif(n = 1, min = P + 500, max = 3000), digits = 2)
## QUESTION/ANSWER GENERATION
i <- round((S - P)/P, digits = 2)*100
#
\begin{question}
Qual \'e a taxa de juros simples obtida por uma aplica\c{c}\~ao de \textdollar $\Sexpr{P}$ que, ap\'os um ano, produz um montante de \textdollar$\Sexpr{S}$?
\end{question}
\begin{solution}
Os juros s\~ao calculados por:
\begin{equation}
S = P(1+i \times n) \Rightarrow S = P + Pin \Rightarrow
\end{equation}
\begin{equation}
Pin = S - P \Rightarrow
i = \frac{S-P}{Pn} \Rightarrow i = \frac{S-P}{P}
\end{equation}
O valor absotulo dos juros \'e $\Sexpr{i}$\%.
\end{solution}
%% META-INFORMATION
%% \extype{num}
%% \exsolution{\Sexpr{fmt(abs(tstat), 3)}}
%% \exname{t statistic}
%% \extol{0.01}
For example, when I need ç I just use \c{c} and so on. BUT, I have been trying to use Rmarkdown instead of Rnw files. And the same example in Rmd:
---
output: pdf_document
---
```{r data generation, echo = FALSE, results = "hide"}
P <- round(runif(n = 1, min = 1000, max = 2000), digits = 2)
S <- round(runif(n = 1, min = P + 500, max = 3000), digits = 2)
i <- round((S - P)/P, digits = 2)*100
```
Question
========
Qual é a taxa de juros simples obtida por uma aplicação de $`r P`
Solution
========
Os juros são calculados por:
\begin{equation}
S = P(1+i \times n) \Rightarrow S = P + Pin \Rightarrow
\end{equation}
\begin{equation}
Pin = S - P \Rightarrow
i = \frac{S-P}{Pn} \Rightarrow i = \frac{S-P}{P}
\end{equation}
O valor absotulo dos juros é `r i`%.
Meta-information
================
extype: num
exsolution: `r round(i, digits = 3)`
exname: Euclidean distance
extol: 0.01
I can compile with RStudio showing the accents correctly:
but when I try:
exams2pdf('file.Rmd', encoding = 'utf8')
it doen't work.
Could someone help me with this issue?
I tried different approaches with the arguments header and inputs of exams2pdf() but none of those gave me the correct output. Also adding LaTeX commands via the YAML header (header-includes) does not work. So I did it the "hard way":
Go to your R library and find the location where the package exams is saved. Inside navigate to the tex folder. There you will find the different templates used by exams. Create a copy of the default template plain.tex and call this duplicate plain_pt.tex. Inside that file you add
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[portuguese]{babel}
to the preamble. Save the file.
The full path on my OSX machine:
/Library/Frameworks/R.framework/Versions/3.3/Resources/library/exams/tex
In Linux can be:
~/R/x86_64-pc-linux-gnu-library/3.3/Resources/library/exams/tex
Now, when calling exams2pdf you can choose your new template with template = 'plain_pt'.
This should also work for other languages by adding the appropriate LaTeX commands.
Thanks to #MartinDabbelJuSmelter for his reply which essentially captures what is going on. However, there are simpler solutions for this. The easiest is:
exams2pdf("file.Rmd", encoding = "UTF-8", template = "plain8")
which leads to the desired output. Now why is this so complicated and why is it so poorly documented?
It is complicated because of the modular structure of the exams package. There are so many different ways to combine the different building blocks that something as easy as this requires two arguments. First, you have to declare that the file.Rmd is in encoding UTF-8. Second, you have to use a template that supports UTF-8. The exams package ships with a simple plain template with UTF-8 enabled.
There are not more LaTeX templates in different encodings etc. because we expected that almost all users will want to use their own custom template anyways. For example, to display the name of their university or their course or to use a particular style/font/etc.
If you only have single-choice (schoice) or multiple-choice (mchoice) questions, then there is also exams2nops which offers a standardized format where it is much simpler to use (but also with less customization). For an impression, see:
exams2nops(c("anova.Rmd", "tstat2.Rmd"),
language = "pt", encoding = "UTF-8")
So you cannot use your num question file.Rmd for this. But the big advantage if you turned it into an schoice question would be that you get automatic scanning and evaluation for exams2nops.
So now for the Achilles heel: the poor documentation. In my defense, I have to say that in Section 2.3 (Creating the first exam) of vignette("exams2", package = "exams") the encoding issue is briefly discussed and it is recommended to look at the output of exams_skeleton() to see how this works. So in your case
exams_skeleton(markup = "markdown", encoding = "UTF-8")
should have provided some useful examples.
But arguably this ought to be easier to find. A better documentation web page for exams is high on my wish list - especially for guiding newcomers - but this summer I didn't find the necessary time. Hopefully next year...
P.S.: The following lines at the start of the Rmd file are completely unnecessary and ignored by exams:
---
output: pdf_document
---
The output into which each exercise is rendered is determined by the exams2xyz functions and not the exercise files themselves. For example:
exams2html("foo.Rmd", encoding = "UTF-8", template = "plain8")
The reason for the function (rather than the Rmd file) deciding about this is simple: Users typically want to build a large pool of questions and then might want to use the same question in a PDF file (for a written exam) or for Moodle or for live voting via ARSnova etc. If you had to modify the question pool each time for this (or keep copies) that would be rather cumbersome.

Resources