Unwanted sanitizing (escaping) in knitr due to update - r

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

Related

referencing latex table in quarto

I have the following table in my quarto document and I would like to reference it automatically in my text.
Quarto understands that this is my second table and is able to name it Table 2 in the caption but I can't find a way to reference this table automatically in my text.
I have this line in my YAML to make the table work.
---
format: pdf
header-includes:
- \usepackage{multirow}
---
```{=latex}
\begin{table}[]
\caption{Summary of the different variabilities when comparing marks from same or different tools and zones}
\label{Variabilities}
\begin{center}
\begin{tabular}{ll|cc|}
\cline{3-4}
& & \multicolumn{2}{c|}{\textbf{Tool}} \\ \cline{3-4}
& & \multicolumn{1}{l|}{\textit{Same}} & \multicolumn{1}{l|}{\textit{Different}} \\ \hline
\multicolumn{1}{|c|}{\multirow{2}{*}{\textbf{Zone}}} & \textit{Same} & \multicolumn{1}{c|}{W} & B \\ \cline{2-4}
\multicolumn{1}{|c|}{} & \textit{Different} & \multicolumn{1}{c|}{B} & B \\ \hline
\end{tabular}
\end{center}
\end{table}
```
If anyone knows how to give this table a label that I can call in the text for referencing.
HERE IS THE ANSWER TO THIS
Two more lines have to be introduced to the YAML in order to use the package cleveref
---
format: pdf
header-includes:
- \usepackage{multirow}
- \usepackage{hyperref}
- \usepackage[capitalise,noabbrev]{cleveref}
---
The way the table is written does not change.
To reference the table in the text as "Table X", you have to write
\ref{Variabilities}
(because I have \label{Variabilities} in my table).
Thanks #samcarter_is_at_topanswers.xyz for your help
You can use the \cref{Variabilities} from the cleveref package:
\documentclass{article}
\usepackage{multirow}
\usepackage[capitalise,noabbrev]{cleveref}
\begin{document}
\begin{table}[]
\caption{Summary of the different variabilities when comparing marks from same or different tools and zones}
\label{Variabilities}
\begin{center}
\begin{tabular}{ll|cc|}
\cline{3-4}
& & \multicolumn{2}{c|}{\textbf{Tool}} \\ \cline{3-4}
& & \multicolumn{1}{l|}{\textit{Same}} & \multicolumn{1}{l|}{\textit{Different}} \\ \hline
\multicolumn{1}{|c|}{\multirow{2}{*}{\textbf{Zone}}} & \textit{Same} & \multicolumn{1}{c|}{W} & B \\ \cline{2-4}
\multicolumn{1}{|c|}{} & \textit{Different} & \multicolumn{1}{c|}{B} & B \\ \hline
\end{tabular}
\end{center}
\end{table}
\cref{Variabilities}
\end{document}
Two more lines have to be introduced to the YAML in order to use the package cleveref
---
format: pdf
header-includes:
- \usepackage{multirow}
- \usepackage{hyperref}
- \usepackage[capitalise,noabbrev]{cleveref}
---
The way the table is written does not change. To reference the table in the text as "Table X", you have to write
\ref{Variabilities}
(because I have \label{Variabilities} in my table).
Thanks #samcarter_is_at_topanswers.xyz for your help

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

rmarkdown matrices not functioning as expected or seen in rstudio

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'

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.

Rmd/Kntir: Markdown citations in LaTeX environments

I want to create a threeparttable in a Rmd/Knitr-document and to add a note to the bottom of the table. The table is created by a R-function inside a chunk with results = "asis". I did not add the function to the working example because it's quite verbose and the problem is evident from the pure LaTeX code.
This works and the result looks as expected.
---
title: "Untitled"
output: pdf_document
header-includes:
- \usepackage{threeparttable}
- \usepackage{booktabs}
- \usepackage{longtable}
references:
- id: rao2001basic
title: Basic Research in Parapsychology
author:
- family: Rao
given: K.R.
issued:
year: 2001
publisher: McFarland
type: book
---
\begin{table}[h]
\centering
\begin{threeparttable}
\caption{A summary table of the cars dataset.}
\begin{tabular}{lrr}
\toprule
Descriptives & speed & dist\\
\midrule
Mean & 15.4 & 42.98\\
SD & 5.29 & 25.77\\
Min & 4 & 2\\
Max & 25 & 120\\
\bottomrule
\end{tabular}
\tablenotes{\item\textit{Note.} This table was created by #rao2001basic. }
\end{threeparttable}
\end{table}
Unfortunately, the citation in the table caption is not working. It works fine if I take it out of the LaTeX environment, but not inside. Is there a way to parse the Markdown in the LaTeX environment?
This sort of issue is essentially an escaping issue or rather an avoidance issue of pandoc's automatic latex block begin/end recognition.
This particular case could be written with the environment commands directly as
\table[h]
\centering
\threeparttable
\caption{A summary table of the cars dataset.}
\begin{tabular}{lrr}
\toprule
Descriptives & speed & dist\\
\midrule
Mean & 15.4 & 42.98\\
SD & 5.29 & 25.77\\
Min & 4 & 2\\
Max & 25 & 120\\
\bottomrule
\end{tabular}
\tablenotes[flushleft]
\item\textit{Note.} This table was created by #rao2001basic.
\endtablenotes
\endthreeparttable
\endtable
but if the begin{env}/end{env} are truly needed then macros can be used like this
\def \btable{\begin{table}}
\def \etable{\end{table}}
\def \bthreeparttable{\begin{threeparttable}}
\def \ethreeparttable{\end{threeparttable}}
\def \btablenotes{\begin{tablenotes}}
\def \etablenotes{\end{tablenotes}}
It would be nice if a robust generic solution existed for renaming of begin{env}/end{env} that could allow selective markdown within tex blocks. Something like...
\newcommand\mdbegin[2]{%
\ifstrempty{#1}{%
\begin{#2}
}{%
\begin{#1}[#2]
}%
}
\newcommand\mdend[1]{%
\end{#1}
}
which works for this, using the etoolbox package, but I don't think it would be a recommended solution.
I found that if you are willing to use the bookdown::pdf_document2() format, you can use text references to solves this problem without having to mess with LaTeX:
---
title: "Untitled"
output: bookdown::pdf_document2
header-includes:
- \usepackage{threeparttable}
- \usepackage{booktabs}
- \usepackage{longtable}
references:
- id: rao2001basic
title: Basic Research in Parapsychology
author:
- family: Rao
given: K.R.
issued:
year: 2001
publisher: McFarland
type: book
---
(ref:tablenote)
This table was created by #rao2001basic.
\begin{table}[h]
\centering
\begin{threeparttable}
\caption{A summary table of the cars dataset.}
\begin{tabular}{lrr}
\toprule
Descriptives & speed & dist\\
\midrule
Mean & 15.4 & 42.98\\
SD & 5.29 & 25.77\\
Min & 4 & 2\\
Max & 25 & 120\\
\bottomrule
\end{tabular}
\tablenotes{\item\textit{Note.} (ref:tablenote)}
\end{threeparttable}
\end{table}
This even works when tables are created by in R:
```{r results = "asis"}
knitr::kable(mtcars[1:3, ], caption = "(ref:tablenote)")
```

Resources