rmarkdown matrices not functioning as expected or seen in rstudio - r

I am trying create a blogdown post using Rmarkdown but the matrix I am trying to create is not giving the correct output. In Rstudio it looks like the image below, however when I run the rmarkdown I get a different result.
Gives output in blogdown:
Rmarkdown code:
$$
\left(\begin{array}{cccc}
\text{var } & ... & -1 \\
\text{cov } & ... & ...\\
\text{mat } & ... & -1 \\
... & ... & -1\\
1 & ... & 0
\end{array}\right)
\left(\begin{array}{c}
w_{1} \\
... \\
... \\
... \\
w_{k} \\
\lambda
\end{array}\right)
=
\left(\begin{array}{c}
0 \\
... \\
... \\
... \\
0 \\
1
\end{array}\right)
$$
Any ideas on where I am going wrong and how I can make a matrix equation be on the same line as in the RStudio output?

The empty lines are breaking things. From https://tex.stackexchange.com/q/230338
An empty line in TeX should never be used just to arrange the source. It is an instruction exactly the same as the command \par which ends a paragraph and starts TeX's line breaking algorithm to split a paragraph into lines.
So it is not allowed in display math and it should never be used on the line before display math either, in that position it does not generate an error but forces TeX to take recovery action that produces a spurious white paragraph on the line above the display.
David Carlisle, Feb 26 '15 at 21:29
While it might not seem obvious that a LaTeX limitation would impose itself on an HTML target, the rendering uses MathJax (javascript library) that renders LaTeX math mode.
If you remove them, it seems to render correctly.
---
title: Quux
output: html_document
---
$$
\left(\begin{array}{cccc}
\text{var } & ... & -1 \\
\text{cov } & ... & ...\\
\text{mat } & ... & -1 \\
... & ... & -1\\
1 & ... & 0
\end{array}\right)
\left(\begin{array}{c}
w_{1} \\
... \\
... \\
... \\
w_{k} \\
\lambda
\end{array}\right)
=
\left(\begin{array}{c}
0 \\
... \\
... \\
... \\
0 \\
1
\end{array}\right)
$$
It also works with output: pdf_document:
R.version
# _
# platform x86_64-w64-mingw32
# arch x86_64
# os mingw32
# system x86_64, mingw32
# status
# major 3
# minor 5.3
# year 2019
# month 03
# day 11
# svn rev 76217
# language R
# version.string R version 3.5.3 (2019-03-11)
# nickname Great Truth
packageVersion("knitr")
# [1] '1.23'
packageVersion("rmarkdown")
# [1] '1.13'

Related

R markdown: Using R code within latex table

I have a finished latex table like this one loaded into r markdown.
\begin{table}[!h]
\centering
\begin{tabular}{|c|c|}
\hline
$\textbf{Details}$ & \\
\midrule[1pt]
\specialrule{2pt}{-2pt}{-2pt}
\specialrule{2pt}{0pt}{0.5pt}
Name der Sitzung & $A$
\\ \hline
erstellt am & $XXXXXX$ \\ \hline
erstellt von & $x$ \\ \hline
Zeitpunkt Auswertung & $x$ \\ \hline
Anzahl Teilnehmer & $x$ \\ \hline
Anzahl Stimmen & $x$ \\ \hline
Anzahl Fragen & $x$ \\ \hline
\end{tabular}
\end{table}
The part $XXXXX$ is supposed to be replaced by the following R code: DATA$TABLE[[1]]$a[[1]].
How can i do that?
When I plug in
´´´{r}
Table[[1]]$a[[1]]
´´´
for $XXXXX$, I get an error message:
output file: dynmaicMarkdown.knit.md
! You can't use `macro parameter character #' in math mode.
l.124 #
# NULL
Fehler: LaTeX failed to compile dynmaicMarkdown.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See dynmaicMarkdown.log for more info.
Zusätzlich: Warnmeldung:
In has_crop_tools() :
Tool(s) not installed or not in PATH: pdfcrop, ghostscript
-> As a result, figure cropping will be disabled.
Ausführung angehalten

Unwanted sanitizing (escaping) in knitr due to update

Last Spring, I used code similar to my minimum working example (MWE) below to make this: https://cdn.advocacy.sba.gov/wp-content/uploads/2019/04/23142650/2019-Small-Business-Profiles-MA.pdf
According to the knitr documentation, the table code should not get sanitized. If you knit the MWE however, you will see that several characters do get sanitized (escaped). For example, \ is sometimes turned into \textbackslash{}. So, it seems that some package update has changed when code gets sanitized. If you simply copy the RMD table code from below and paste it into the TeX output, it compiles fine.
I have tried reverting back to many of last year's packages, yet to no avail.
---
title: "MWE"
output:
pdf_document:
keep_tex: yes
---
\begin{tabular}{#{}lll}
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
\end{tabular}
*[In my original code it was part of an "asis" chunk. You can try this, and find the same problem.]
This is a known problem and the solution is to add raw attributes to pandoc, which ensures that content inside the block is not escaped.
1) Add md_extensions: +raw_attribute
2) Add a latex block
For your examples this works as follows:
---
title: "MWE"
output:
pdf_document:
md_extensions: +raw_attribute
keep_tex: yes
---
```{=latex}
\begin{tabular}{#{}lll}
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
&
\begin{tabular}{ll}
A & B \\
A & B \\
\end{tabular}
\end{tabular}
```
or when using it inside a code chunk:
```{r, results = "asis"}
cat("```{=latex}")
// your latex code
cat("```")
```
P.S.: pandoc version 2.0.0 is needed for this feature

Knitr chunk plots within a latex table - size issues

I am writing a report within R studio using the knitr package. I am trying to succinctly describe a list of variables and there inclusion in an analysis. In order to do this I am using the long table package within latex. I have inserted a chunk into one of the table columns in order to display a histogram of some of the data. The issue is that this disrupts the width of the table column. I have tried setting the table width within the latex code but something is happening within the chunk that is over riding this.
\documentclass{article}
\usepackage{float}
\usepackage{longtable}
\begin{document}
<<ch-req, echo=FALSE,results='hide',include=FALSE>>=
require(datasets)
#
\begin{center}
\begin{longtable}{|c|p{.45\textwidth}|c|}
\caption{Summary table for variables in 'cars' data set} \label{tab:csumTab} \\
\hline \multicolumn{1}{|c|}{\textbf{Variable Original Name}} & \multicolumn{1}{c|}{\textbf{Variable Summary}} & \multicolumn{1}{c|}{\textbf{Renamed Variable}} \\ \hline\hline
\endfirsthead
\multicolumn{3}{c}%
{{\bfseries \tablename\ \thetable{} -- continued from previous page}} \\
\hline \multicolumn{1}{|c|}{\textbf{Variable Original Name}} &
\multicolumn{1}{c|}{\textbf{Variable Summary}} &
\multicolumn{1}{c|}{\textbf{Renamed Variable}} \\ \hline
\endhead
\hline \multicolumn{3}{r}{{Continued on next page}} \\
\endfoot
\hline \hline
\endlastfoot
`speed' & numeric Speed (mph) of the car & \\
&
\begin{figure}[H]
<<histspeed1,echo=FALSE, fig=TRUE,out.width='2in', fig.align = 'left'>>=
hist(cars$speed)
#
\end{figure}
& \\
\hline
`dist' & This is the numeric stopping distance of the car (ft)& `Distance'\\
& \begin{tabular}{|c|c|c|}
\hline
min & median & max \\
\hline
2 & 36 & 120 \\
\hline
\end{tabular}& \\
\end{longtable}
\end{center}
\begin{center}
\begin{longtable}{|c|p{.45\textwidth}|c|}
\caption{Summary table for variables in `cars' data set} \label{tab:csumTab} \\
\hline \multicolumn{1}{|c|}{\textbf{Variable Original Name}} & \multicolumn{1}{c|}{\textbf{Variable Summary}} & \multicolumn{1}{c|}{\textbf{Renamed Variable}} \\ \hline\hline
\endfirsthead
\multicolumn{3}{c}%
{{\bfseries \tablename\ \thetable{} -- continued from previous page}} \\
\hline \multicolumn{1}{|c|}{\textbf{Variable Original Name}} &
\multicolumn{1}{c|}{\textbf{Variable Summary}} &
\multicolumn{1}{c|}{\textbf{Renamed Variable}} \\ \hline
\endhead
\hline \multicolumn{3}{r}{{Continued on next page}} \\
\endfoot
\hline \hline
\endlastfoot
`speed' & numeric Speed (mph) of the car & \\
&
\begin{figure}[H]
%<<histspeed2,echo=FALSE, fig=TRUE,out.width='2in', fig.align = 'left'>>=
%hist(cars$speed)
%#
\end{figure}
& \\
\hline
`dist' & This is the numeric stopping distance of the car (ft)& `Distance'\\
& \begin{tabular}{|c|c|c|}
\hline
min & median & max \\
\hline
2 & 36 & 120 \\
\hline
\end{tabular}& \\
\end{longtable}
\end{center}
\end{document}
There are two tables just to show that the table size does work when the plot is not incorporated in the code. I have used out.width='2in' to change the size of the histogram in the table, but there is still a large area reserved for the plot by default(?). You can see this more clearly if you change fig.align = 'left' to fig.align = 'center'. I want the table to look how it does in the second example but with the plot incorporated.
Any help greatly appreciated.

Different behavior between pdf_document and bookdown::pdf_document2 when using compareGroups

I am having an issue when knit-ing documents using bookdown::pdf_document2 that don't appear when using the standard pdf_document.
Specifically, I am using the compareGroups library and the export2md function to output comparison tables such as the one shown below:
This is successful when I use output:pdf_document. However, The table is not properly created when I use output: bookdown:pdf_document2.
There are clearly differences in the tex files and I am manually able to copy the table from the tex outputed by pdf_document to pdf_document2. Does anyone have any thoughts on how to get bookdown to correctly create the table? I have create a repo with my bug found here for more details: https://github.com/vitallish/bookdown-bug
Overview
bookdown::pdf_document2() is different from rmarkdwon::pdf_document(), the former set $opts_knit$kable.force.latex to TRUE while the latter leaves that to default value (FALSE).
check .md file
I think that the process from .md to .tex should be the same, and the difference in .tex files might due to the difference in .md files. So I run the following code to keep the intermediate .md files.
rmarkdown::render('pdf_document.Rmd', clean = FALSE)
file.remove('pdf_document.utf8.md');
rmarkdown::render('pdf_document2.Rmd', clean = FALSE)
file.remove('pdf_document2.utf8.md');
pdf_document.knit.md
Table: Summary descriptives table by groups of `Sex'
Var Male N=1101 Female N=1193 p.overall
----------------------------------------------- --------------- ----------------- -----------
Recruitment year: 0.506
1995 206 (18.7%) 225 (18.9%)
2000 390 (35.4%) 396 (33.2%)
2005 505 (45.9%) 572 (47.9%)
Age 54.8 (11.1) 54.7 (11.0) 0.840
Smoking status: <0.001
Never smoker 301 (28.1%) 900 (77.5%)
Current or former < 1y 410 (38.3%) 183 (15.7%)
Former >= 1y 360 (33.6%) 79 (6.80%)
Systolic blood pressure 134 (18.9) 129 (21.2) <0.001
Diastolic blood pressure 81.7 (10.2) 77.8 (10.5) <0.001
pdf2_document.knit.md
\begin{table}
\caption{(\#tab:md-output)Summary descriptives table by groups of `Sex'}
\centering
\begin{tabular}[t]{l|c|c|c}
\hline
Var & Male N=1101 & Female N=1193 & p.overall\\
\hline
Recruitment year: & & & 0.506\\
\hline
\ \ \ \ 1995 & 206 (18.7\%) & 225 (18.9\%) & \\
\hline
\ \ \ \ 2000 & 390 (35.4\%) & 396 (33.2\%) & \\
\hline
\ \ \ \ 2005 & 505 (45.9\%) & 572 (47.9\%) & \\
\hline
Age & 54.8 (11.1) & 54.7 (11.0) & 0.840\\
\hline
Smoking status: & & & <0.001\\
\hline
\ \ \ \ Never smoker & 301 (28.1\%) & 900 (77.5\%) & \\
\hline
\ \ \ \ Current or former < 1y & 410 (38.3\%) & 183 (15.7\%) & \\
\hline
\ \ \ \ Former >= 1y & 360 (33.6\%) & 79 (6.80\%) & \\
\hline
Systolic blood pressure & 134 (18.9) & 129 (21.2) & <0.001\\
\hline
Diastolic blood pressure & 81.7 (10.2) & 77.8 (10.5) & <0.001\\
\hline
\end{tabular}
\end{table}
That explains why you see different appearance in the pdf output.
explore
To further explore the reason,
> pdf1 <- rmarkdown::pdf_document()
> pdf2 <- bookdown::pdf_document2()
> all.equal(pdf, pdf2)
[1] "Length mismatch: comparison on first 11 components"
[2] "Component “knitr”: Component “opts_knit”: target is NULL, current is list"
[3] "Component “pandoc”: Component “args”: Lengths (8, 12) differ (string compare on first 8)"
[4] "Component “pandoc”: Component “args”: 8 string mismatches"
[5] "Component “pandoc”: Component “ext”: target is NULL, current is character"
[6] "Component “pre_processor”: target, current do not match when deparsed"
[7] "Component “post_processor”: target is NULL, current is function"
Since knitr convert Rmarkdown to pandoc markdown, I guess $knitr cause the difference in .md files.
> all.equal(pdf$knitr, pdf2$knitr)
[1] "Component “opts_knit”: target is NULL, current is list"
> pdf2$knitr$opts_knit
$bookdown.internal.label
[1] TRUE
$kable.force.latex
[1] TRUE
kable is a function to output table, so $knitr$opts_knit$kable.force.latex might to the root reason.
verify
To test my assumption,
pdf3 <- pdf2
pdf3$knitr$opts_knit$kable.force.latex = FALSE
rmarkdown::render('pdf_document3.Rmd', clean = FALSE, output_format = pdf3)
file.remove('pdf_document3.utf8.md')
pdf_document3.knit.md
Var Male N=1101 Female N=1193 p.overall
----------------------------------------------- --------------- ----------------- -----------
Recruitment year: 0.506
1995 206 (18.7%) 225 (18.9%)
2000 390 (35.4%) 396 (33.2%)
2005 505 (45.9%) 572 (47.9%)
Age 54.8 (11.1) 54.7 (11.0) 0.840
Smoking status: <0.001
Never smoker 301 (28.1%) 900 (77.5%)
Current or former < 1y 410 (38.3%) 183 (15.7%)
Former >= 1y 360 (33.6%) 79 (6.80%)
Systolic blood pressure 134 (18.9) 129 (21.2) <0.001
Diastolic blood pressure 81.7 (10.2) 77.8 (10.5) <0.001
Wa oh!
Advanced
Actually compareGroups::export2md use knitr::kable as the working horse,
> compareGroups::export2md
function (x, which.table = "descr", nmax = TRUE, header.labels = c(),
caption = NULL, ...)
{
if (!inherits(x, "createTable"))
stop("x must be of class 'createTable'")
...
if (ww %in% c(1)) {
...
table1 <- table1[-1, , drop = FALSE]
return(knitr::kable(table1, align = align, row.names = FALSE,
caption = caption[1]))
}
if (ww %in% c(2)) {
table2 <- prepare(x, nmax = nmax, c())[[2]]
...
return(knitr::kable(table2, align = align, row.names = FALSE,
caption = caption[2]))
}
}
which use kable.force.latex as an internal option to adjust its output. If your browse the GitHub repository of knitr, you can find the following code in the R/utils.R file
kable = function(
x, format, digits = getOption('digits'), row.names = NA, col.names = NA,
align, caption = NULL, format.args = list(), escape = TRUE, ...
) {
# determine the table format
if (missing(format) || is.null(format)) format = getOption('knitr.table.format')
if (is.null(format)) format = if (is.null(pandoc_to())) switch(
out_format() %n% 'markdown',
latex = 'latex', listings = 'latex', sweave = 'latex',
html = 'html', markdown = 'markdown', rst = 'rst',
stop('table format not implemented yet!')
) else if (isTRUE(opts_knit$get('kable.force.latex')) && is_latex_output()) {
# force LaTeX table because Pandoc's longtable may not work well with floats
# http://tex.stackexchange.com/q/276699/9128
'latex'
} else 'pandoc'
if (is.function(format)) format = format()
...
structure(res, format = format, class = 'knitr_kable')
}
Conclusion
$knitr$opts_knit$kable.force.latex = TRUE cause bookdown::pdf_document2() to insert latex code in the .md file, while rmarkdown::pdf_document() preserves the markdown code, which leaves pandoc the chance to give a pretty table.
I don't think this is a bug. Yihui Xie (the author of bookdown) might have some special reason to do this. And bookdown::pdf_document2() never need to be the same as rmarkdown::pdf_document().
This problem with export2md has been solved in the latest version of compareGroups package (4.0) available on github. You can install this newest version by typing:
library(devtools)
devtools::install_github("isubirana/compareGroups")
I hope this version will be submitted to CRAN very soon.

Remove additional footnote from R's xtable() table output in LaTeX

I am using the following R code to call xtable and generate a LaTeX table for a Sweave document.
ifelse(LaTeX==1, print(xtable(rule1.results.noTC, caption="Rule 1 Results 0 Transaction Costs",
digits=c(1,2,4,4,4), display=c("d","d","f","f","f"))),
print(rule1.results))
This produces the following LaTeX
% latex table generated in R 3.0.1 by xtable 1.7-1 package
% Sun Jul 28 16:54:42 2013
\begin{table}[ht]
\centering
\begin{tabular}{rrrrr}
\hline
& L & profits & annCumulExReturn & sharpe \\
\hline
1 & 5 & -888.8215 & -0.1501 & -4.3939 \\
2 & 10 & -909.8941 & -0.1533 & -6.8882 \\
3 & 20 & -893.6245 & -0.1509 & -6.9081 \\
4 & 40 & -865.6764 & -0.1466 & -9.8462 \\
5 & 80 & -832.4700 & -0.1417 & -11.7260 \\
6 & 160 & -757.0690 & -0.1305 & -16.3088 \\
7 & 320 & -626.9162 & -0.1118 & -31.6134 \\
8 & 640 & -340.8740 & -0.0730 & -44.2321 \\
\hline
\end{tabular}
\caption{Rule 1 Results with Transaction Costs}
\end{table}
When I convert this to pdf, I get a nice table. However, it is followed by a weird note:
[1] "
And I get several of these if I plot multiple tables in a row. How can I eliminate this either via R's xtable or by editing the LaTeX code.
Thanks
I can't say for sure without your data and an example of the .tex file, but I'm pretty confident this is due to your use of ifelse. I imagine the following will not give you the weird print out:
if(LaTeX==1) {
print(xtable(rule1.results.noTC,caption="Rule 1 Results 0 Transaction Costs",
digits=c(1,2,4,4,4), display=c("d","d","f","f","f")))
} else {
print(rule1.results))
}
This is because ifelse returns its result, which you're also printing. See, for example:
> ifelse(TRUE,print("true"),print("false"))
[1] "true"
[1] "true"

Resources