I am having difficulty getting LaTeX math expressions to properly render when using knitr and kableExtra to compile a table in a Beamer presentation. I was originally use xelatex as my engine, and then switched to pdflatex to see if this would resolve the issue. I'm stumped on this one.
TeX preamble
% For resizing caption font size
\usepackage{caption}
\captionsetup[figure]{font=tiny}
% Other packages
\usepackage{fancyvrb}
\usepackage{color,xcolor}
\usepackage{framed}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{array}
\usepackage{multirow}
\usepackage{wrapfig}
\usepackage{float}
\usepackage{colortbl}
\usepackage{pdflscape}
\usepackage{tabu}
\usepackage{threeparttable}
\usepackage{threeparttablex}
\usepackage[normalem]{ulem}
\usepackage{makecell}
% Colour formatting
\definecolor{UBCblue}{rgb}{0.04706, 0.13725, 0.26667} % UBC Blue (primary)
\definecolor{UBCgrey}{rgb}{0.3686, 0.5255, 0.6235} % UBC Grey (secondary)
\setbeamercolor{title}{fg=UBCblue} % slide title
\setbeamercolor{frametitle}{fg=UBCblue} % slide title
\setbeamercolor{structure}{fg=darkgray} % more list stuff, I think
\setbeamertemplate{itemize items}[circle] % for list itemes
% Page numbers
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{footline}[page number]
% Margins
\setbeamersize{text margin left=8mm,text margin right=8mm}
% make code-output smaller
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{fontsize=\footnotesize,commandchars=\\\{\}}
% make console-output smaller:
\makeatletter
\def\verbatim{\footnotesize\#verbatim \frenchspacing\#vobeyspaces \#xverbatim}
\makeatother
\setlength{\parskip}{0pt}
\setlength{\OuterFrameSep}{-4pt}
\makeatletter
\preto{\#verbatim}{\topsep=-10pt \partopsep=-10pt }
\makeatother
% For better spacing between the list bullets
\renewcommand{\tightlist}{\setlength{\itemsep}{1ex}\setlength{\parskip}{0pt}}
RMarkdown Document
---
title: "My Title"
subtitle: "My Subtitle"
author: Speleo4Life
date: "March 11th, 2021"
output:
beamer_presentation:
latex_engine: pdflatex
includes:
in_header: preamble.tex
theme: "default"
colortheme: "orchid"
fonttheme: "serif"
slide_level: 2
keep_tex: true
urlcolor: blue
linkcolor: purple
---
```{r setup, eval=TRUE, include=FALSE, echo=FALSE}
library(tidyverse)
library(ggplot2)
library(kableExtra)
library(psych)
```
```{r, eval=TRUE, echo=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(knitr.table.format = "latex")
```
## Review: Null Hypothesis Significance Testing
```{r, echo=FALSE}
c1 <- c('$\\text{Reject } H_0$', '$\\text{Retain } H_0$')
c2 <- c('$\\text{Type I Error } (\\alpha)$', 'Correct Retention')
c3 <- c('$\\text{Power } (1-\\beta)$', '$\\text{Type II Error } \\beta$')
df <- data.frame(c1,c2,c3)
colnames(df) <- c('$\\textbf{Decision}$', '$\\mathbf{H_0} \\textbf{\\textit{is true}}$',
'$\\mathbf{H_0} \\textbf{\\textit{is false}}$')
kbl(df, booktabs = T) %>%
add_header_above(c(" ", "State of Reality" = 2))
```
Relevant Output
Just add escape = F to kbl:
---
title: "My Title"
subtitle: "My Subtitle"
author: Speleo4Life
date: "March 11th, 2021"
output:
beamer_presentation:
latex_engine: pdflatex
includes:
in_header: preamble.tex
theme: "default"
colortheme: "orchid"
fonttheme: "serif"
slide_level: 2
keep_tex: true
urlcolor: blue
linkcolor: purple
---
```{r setup, eval=TRUE, include=FALSE, echo=FALSE}
library(tidyverse)
library(ggplot2)
library(kableExtra)
library(psych)
```
```{r, eval=TRUE, echo=FALSE}
knitr::opts_chunk$set(echo = TRUE)
options(knitr.table.format = "latex")
```
## Review: Null Hypothesis Significance Testing
```{r, echo=FALSE}
c1 <- c('$\\text{Reject } H_0$', '$\\text{Retain } H_0$')
c2 <- c('$\\text{Type I Error } (\\alpha)$', 'Correct Retention')
c3 <- c('$\\text{Power } (1-\\beta)$', '$\\text{Type II Error } \\beta$')
df <- data.frame(c1,c2,c3)
colnames(df) <- c('$\\textbf{Decision}$', '$\\mathbf{H_0} \\textbf{\\textit{is true}}$',
'$\\mathbf{H_0} \\textbf{\\textit{is false}}$')
kbl(df, booktabs = T, escape = F) %>%
add_header_above(c(" ", "State of Reality" = 2))
```
-output
Related
Could you please help me in finding the right code to print a png image inside a R flexdashboard?
Here my code chunk:
---
title: "Analyse des installations PV - Les Vergers"
author: "Dario Santandrea"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
flexdashboard::flex_dashboard:
orientation: rows
vertical_layout: fill
runtime: shiny
---
First attempt
renderImage({
outfile <- tempfile(fileext = "X:/LesVergers/Analyse/BilanSolaire/Figures/Solar_angle_scheme.png")
png(outfile, width = 500, height = 400)
dev.off()
}
)
Second attempt
#knitr::include_graphics("X:/LesVergers/Analyse/BilanSolaire/Figures/Solar_angle_scheme.png")
The image i've been trying to print doesn't simply appear in the flexdashboard
flexdashboard is essentially Markdown. Thus see e.g. this related thread.
```{r picture, echo = F, fig.cap = "Title", out.width = '100%'}
knitr::include_graphics("picture.png")
```
Just place this chunk within the standard flexdashboard layout:
BLOCK1
=====================================
Row {data-width=1000}
-----------------------------------------------------------------------
### A picture
```{r picture, echo = F, fig.cap = "Title", out.width = '100%'}
knitr::include_graphics("picture.png")
```
I have the following code in an rmd file which leverages tikz for diagrams:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
Prove tikz works:
```{r tikTest1, engine = "tikz"}
\usetikzlibrary{shapes}
\begin{tikzpicture}
\node[ellipse, draw=black, align = center] (Data) {Data $y_{n}$};
\end{tikzpicture}
```
Then, when you set `eval = TRUE` in the below code, it will not work.
```{r tikTest2, eval = FALSE, engine = "tikz"}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
When changing to eval=TRUE in the second chunk, I get the following
error:
Quitting from lines 24-29 (testNonTufteLua.Rmd) Error: running
'texi2dvi' on '.\tikz36747a021b22.tex' failed
LaTeX errors: rarygraphdrawing.code.tex:22: Package pgf Error: You
need to run LuaTeX to use the graph drawing library.
This error occurs when using the knit button from RStudio or using render("testNonTufteLua.Rmd", output_format = pdf_document(keep_tex = TRUE, latex_engine = "lualatex"). I have also experimented with setting options(tikzDefaultEngine = "luatex") to get tikzDevice to handle it properly, but it still does not work. I just can't seem to get the graphdrawing library to work even though the tikz-shapes library can be loaded and also that the rest of the document seems to be compiled with lualatex. Thanks for any help!!
Update: Meanwhile knitr no longer uses tools::texi2dvi but tinytex::latexmk. One therefore has to use options(tinytex.engine = 'lualatex') in a set-up chunk.
This is rather tricky, since you are not using tikzDevice but the tikz engine, which uses tools::texi2dvi to convert to PDF. You can change this using options(texi2dvi = "lualatex"). However, the default template does not work with LuaLaTeX. I have therefore created a modified template:
\RequirePackage{luatex85}
\documentclass{article}
\usepackage[luatex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
And specify that file with engine.opts = list(template = "tikz2pdf.tex"). Putting it all together here my working file:
---
title: "TestNonTufteLua"
author: "Me"
output:
pdf_document :
latex_engine: lualatex
---
```{r}
options(texi2dvi = "lualatex")
```
```{r tikTest2, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
Result:
References:
how to set engine options
preview and LuaLaTeX
knitr using texi2pdf
A small running variation of the example above is the following using tinytex.
---
title: "lualatex. Using `tinytex.engine`"
output:
html_document:
df_print: paged
pdf_document:
latex_engine: lualatex
---
## Latex engines
By default, PDF documents are rendered using `pdflatex`. You can specify an
alternate engine using the `latex_engine` option. Available engines
are `pdflatex`, `xelatex`, and `lualatex.`
```{r setup}
options(tinytex.engine = "lualatex")
```
```{r tikzLua, eval = TRUE, engine = "tikz", engine.opts = list(template = "tikz2pdf.tex")}
\usetikzlibrary{graphs, graphdrawing}
\usegdlibrary{layered}
\tikz [gr/.style={gray!50}, font=\bfseries]
\graph [layered layout] {
% A and F are horizontally aligned if you also set weight=0.5 for A -- C.
A -- [minimum layers=2] C -- F,
{ [nodes=gr, edges=gr] A -- B -- { E, D -- F } }
};
```
After an update in knitr the example above stopped running.
When I use kable to create a table in my Rnw file, the table outputs as expected. However when I include the caption, the table ceases to output at all. Below is my latex and sample knitr chunk.
\documentclass[titlepage]{article}
\usepackage{graphicx}
\usepackage[dvipsnames]{xcolor}
\usepackage{afterpage}
\usepackage{booktabs}
\usepackage{longtable}
\pagecolor{ForestGreen}\afterpage{\nopagecolor}
\color{white}
\title{%
\noindent\makebox[\linewidth]{\rule{9cm}{0.9pt}}
\huge \textbf{\textit{Key Distributor Report}}\\
\LARGE \vspace{2mm} \textbf{\textit{A detailed quarterly review}} \\
\noindent\makebox[\linewidth]{\rule{9cm}{0.9pt}}
\vspace{6mm} \LARGE Macdonald Corp.}
\pagenumbering{arabic}
\begin{document}
\maketitle
\color{black}
\newpage
\tableofcontents
\newpage
\section{Overview of Key Distributors}
\section{Company A}
\subsection{National Overview}
\subsubsection{Account base structure}
<<
tester, echo=FALSE, message=FALSE, warning=FALSE, results='asis',fig.height=3, fig.width=3, fig.align='center', eval=TRUE >>=
library(knitr)
kable(head(mtcars[,1:3]), booktabs=TRUE, caption='This is a caption')
#
\end{document}
This seems to be a problem of coloring the texts. If you try to select all content in the pdf you realize, that the table is actually there, but the text is white. So simply change the way of coloring the title page (use \color on \maketitle instead of \title):
\documentclass[titlepage]{article}
\usepackage{graphicx}
\usepackage[dvipsnames]{xcolor}
\usepackage{afterpage}
\usepackage{booktabs}
\usepackage{longtable}
\pagecolor{ForestGreen}\afterpage{\nopagecolor}
\title{%
\noindent\makebox[\linewidth]{\rule{9cm}{0.9pt}}
\huge \textbf{\textit{Key Distributor Report}}\\
\LARGE \vspace{2mm} \textbf{\textit{A detailed quarterly review}} \\
\noindent\makebox[\linewidth]{\rule{9cm}{0.9pt}}
\vspace{6mm} \LARGE Macdonald Corp.}
\pagenumbering{arabic}
\begin{document}
{\color{white}%
\maketitle
}
\color{black}
\newpage
\tableofcontents
\newpage
\section{Overview of Key Distributors}
\section{Company A}
\subsection{National Overview}
\subsubsection{Account base structure}
<<tester, echo=FALSE, message=FALSE, warning=FALSE,results='asis',fig.height=3, fig.width=3, fig.align='center', eval=TRUE >>=
library(knitr)
library(kableExtra)
library(dplyr)
kable(head(mtcars[,1:3]), booktabs=T, caption='This is a caption') %>%
kable_styling(latex_options = "hold_position")
#
\end{document}
I am writing a rmarkdown document knitting to pdf with tables taken from portions of lists from the ezANOVA package. The tables are made using the pander package. Toy Rmarkdown file with toy dataset below.
---
title: "Table Doc"
output: pdf_document
---
```{r global_options, include=FALSE}
#set global knit options parameters.
knitr::opts_chunk$set(fig.width=12, fig.height=8, fig.path='Figs/',
echo=FALSE, warning=FALSE, message=FALSE, dev = 'pdf')
```
```{r, echo=FALSE}
# toy data
id <- rep(c(1,2,3,4), 5)
group1 <- factor(rep(c("A", "B"), 10))
group2 <- factor(rep(c("A", "B"), each = 10))
dv <- runif(20, min = 0, max = 10)
df <- data.frame(id, group1, group2, dv)
```
``` {r anova, echo = FALSE}
library(ez)
library(plyr)
library(pander)
# create anova object
anOb <- ezANOVA(df,
dv = dv,
wid = id,
between = c(group1, group2),
type = 3,
detailed = TRUE)
# extract the output table from the anova object, reduce it down to only desired columns
anOb <- data.frame(anOb[[1]][, c("Effect", "F", "p", "p<.05")])
# format entries in columns
anOb[,2] <- format( round (anOb[,2], digits = 1), nsmall = 1)
anOb[,3] <- format( round (anOb[,3], digits = 4), nsmall = 1)
pander(anOb, justify = c("left", "center", "center", "right"))
```
Now I have a few problems
a) For the last three columns I would like to have the column heading in the table aligned in the center, but the actual column entries underneath those headings aligned to the right.
b) I would like to have the column headings 'F' and 'p' in italics and the 'p' in the 'p<.05' column in italics also but the rest in normal font. So they read F, p and p<.05
I tried renaming the column headings using plyr::rename like so
anOb <- rename(anOb, c("F" = "italic(F)", "p" = "italic(p)", "p<.05" = ""))
But it didn't work
In markdown, you have to use the markdown syntax for italics, which is wrapping text between a star or underscore:
> names(anOb) <- c('Effect', '*F*', '*p*', '*p<.05*')
> pander(anOb)
-----------------------------------------
Effect *F* *p* *p<.05*
--------------- ------ -------- ---------
(Intercept) 52.3 0.0019 *
group1 1.3 0.3180
group2 2.0 0.2261
group1:group2 3.7 0.1273
-----------------------------------------
If you want to do that in a programmatic way, you can also use the pandoc.emphasis helper function to add the starts to a string.
But your other problem is due to a bug in the package, for which I've just proposed a fix on GH. Please feel free to give a try to that branch and report back on GH -- I will try to get some time later this week to clean up the related unit tests and merge the branch if everything seem to be OK.
Although the problem described in How to set both column width and text alignment in align argument of xtable? looks the same and solution looks promising I can't get this working.
---
output: pdf_document
header-includes:
- \usepackage{longtable}
- \newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}p{#1}}
---
```{r, results='asis', echo=FALSE, warning=FALSE}
library(xtable)
options(xtable.comment = FALSE)
addtorow <- list()
addtorow$pos <- list()
addtorow$pos[[1]] <- c(0)
addtorow$command <- c(paste("\\hline \n",
"\\endhead \n",
"\\hline \n",
"{\\footnotesize See next page} \n",
"\\endfoot \n",
"\\endlastfoot \n",
sep=""))
irisShort <- head(iris)
print(xtable(irisShort,
digits=rep(0,6),
align=c(
"p{0.015\\textwidth}|",
"R{0.37\\textwidth}|",
"R{0.12\\textwidth}|",
"R{0.08\\textwidth}|",
"R{0.02\\textwidth}|",
"p{0.35\\textwidth}|")))
```
The newcolumntype declaration seems to be wrong in my example, but I don't know how to fix it. The error I'm getting is:
! Undefined control sequence.
<recently read> \newcolumntype
Any ideas how to fix it?