Blogdown fails rendering page as tikzmark library is not found - r

I am using latest version of blogdown and tinytex to render a page containing this snippet:
The following diagram:
```{r, echo=FALSE, engine='tikz', fig.cap='This is it.', engine.opts = list(template = "../latex/header.tex")}
\begin{tikzpicture}[scale=.7, remember picture]
\tikzmath{ \w = 6; \h =4; \x = 2; \y = 1; }
\draw [fill=gray!30,thick] (-\w/2,-\h/2) rectangle (\w/2,\h/2);
\draw [->,thick] (\w/2,0) -- (\w/2+\x,0);
\draw [->,thick] (-\w/2-\x,0) -- (-\w/2,0);
\node [left] at (-\w/2-\x,0) {Input};
\node [right] at (\w/2+\x,0) {Output};
\node [align=left,font=\ttfamily] at (0,0) {\small function(\subnode {sub}{...}) \{\\\hspace{0.2cm}...\\\}};
\draw[−>,thick] (-\w/2,0) -- (-\w/2 + \w/8,0) -- (-\w/2 + \w/8,\h/4) -- ($ (sub)+(-\w/2.5,\h/5) $) -- ($ (sub)+(0,\h/5) $) -- (sub);
\draw [->,thick] (0,0) -- (\w/2,0);
\end{tikzpicture}
```
Where header.tex is:
\documentclass{article}
\include{preview}
\usepackage[pdftex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
% OWN CODE START
\usetikzlibrary{math}
\usetikzlibrary{tikzmark}
\usetikzlibrary{calc}
% OWN CODE END
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
When I run blogdown::build_site(), I get this error:
Quitting from lines 184-195 (mypost.Rmd)
Error: Failed to compile tikz1137adfc9b89.tex. See https://yihui.name/tinytex/r/#debugging for debugging tips. See tikz1137adfc9b89.log for more info.
Execution halted
Error in render_page(f) :
Failed to render 'content/mypost.Rmd'
file tikz1137adfc9b89.tex is (the last lines showing the error):
! Package tikz Error: I did not find the tikz library 'tikzmark'. I looked for
files named tikzlibrarytikzmark.code.tex and pgflibrarytikzmark.code.tex, but n
either could be found in the current texmf trees..
See the tikz package documentation for explanation.
Type H <return> for immediate help.
...
l.9 \usetikzlibrary{tikzmark}
Here is how much of TeX's memory you used:
12142 strings out of 494553
251420 string characters out of 6174236
281626 words of memory out of 5000000
15624 multiletter control sequences out of 15000+600000
3640 words of font info for 14 fonts, out of 8000000 for 9000
14 hyphenation exceptions out of 8191
55i,0n,68p,420b,90s stack positions out of 5000i,500n,10000p,200000b,80000s
! ==> Fatal error occurred, no output PDF file produced!
I am on Mac, on Windows this works :(

Installing the dev version fixes it:
devtools::install_github('yihui/tinytex')

Related

How to avoid "! LaTeX Error: Environment axis undefined" when using include_tikz with pgfplots?

I have successfully included in an R/exams .Rmd file several graphics made in TikZ. The same does not happen when I try to include a plot under pgfplots using include_tikz(). Whenever \begin {axis} and \end {axis} are included, beware of the error "! LaTeX Error: Environment axis undefined".
In the RStudio console the legend appears: "This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format = pdflatex) restricted \ write18 enabled.entering extended mode", even having enabled in TexStudio write-18. None of these messages appear when I include other TikZ graphs other than pgfplots.
Any TikZ graph works when run in TexMaker or TexStudio, which indicates that it is not a problem of the absence of LaTeX libraries or packages.
I include a part of my code, adapted from https://www.latex4technics.com/?note=1HCT:
```{r datos1, echo = FALSE, results = "hide"}
library(exams)
typ <- match_exams_device()
image01<-'
\\begin{tikzpicture}
\\begin{axis}[legend pos=south east]
\\addlegendimage{empty legend}
\\addplot {sqrt(x)};
\\addplot {ln(x)};
\\addlegendentry{\\hspace{-.6cm}\\textbf{A title}}
\\addlegendentry{$\\sqrt{x}$}
\\addlegendentry{$\\ln{x}$}
\\end{axis}
\\end{tikzpicture}
'
```
```{r grafica01, echo = FALSE, results = "asis"}
include_tikz(image01, name = "grafiko1", markup =
"markdown",format = typ,library = c("arrows"),packages =
"booktabs",width = "7cm",header = "\\usepackage{/home/r-
exams/Documentos/NuevoRStudio/Rmarkdowns/
Esqueleto/exercises/schoice/
LaboratorioTikZ/3dplot}")
```
The answer is right there in your question title. You need to include the pgfplots package:
include_tikz(image01, packages = "pgfplots", ...)
The other packages, library, and header arguments from the call in your question are not needed.
The reason is that for include_tikz() you just use the {tikzpicture} code while in the full .tex file that you linked you additionally have:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
...
\end{tikzpicture}
\end{document}
Note the \usepackge{pgfplots} in the second line!

knitr sanitize_fn warning incorporating plots into latex via knit2pdf

I am dynamically generating pdf reports in R using a driver script that calls knit2pdf. My report source is latex, in a .Rnw file, and the call is like this:
knit2pdf("source.Rnw",output=paste0(fname,".tex"),quiet=T)
fname does not contain any dots.
source.Rnw contains:
<<setup, echo=FALSE >>=
opts_chunk$set(fig.path=tempfile(tmpdir="work",pattern=fname,fileext=".pdf"))
#
<<custom-dev, echo=FALSE >>=
my_pdf<-function(file,width,height) {
pdf(file,width=5,height=2)
}
#
<<plot, echo=FALSE, results="asis", dev="my_pdf", fig.ext="pdf">>=
# A ggplot chart
print(g)
#
The reports are fine, but the following warning is generated from
knitr's sanitize_fn:
dots in figure paths replaced with _ ("work/fname_pdfplot")
Clearly, the offending . is coming from the fileext in opts_chunk. However, if I change that fileext to "_pdf", I don't get the plot in the report at all, and latex throws an error about the file (fname_pdfplot-1) not being found.
Ideas on how to (a) do this right so there's no warning, or (b) do this as I'm doing it but suppress this particular warning?
Edit 1:
Here is a working example of source.Rnw without using fileext. This does seem to be closer, because now it breaks with an error due to putting work\fname... in includegraphics rather than work/fname..., and if I change the backslash to a proper slash, it compiles cleanly.
tempfile is returning work\fname..., so perhaps my fix is just to re-escape those backslashes (or replace them with a forward slash). Is this something I should have known to do already?
\documentclass[titlepage]{article}
\usepackage[utf8]{inputenc}
\usepackage[headheight=36pt, foot=24pt, top=1in, bottom=1in, left=1in, right=1in, landscape]{geometry}
\usepackage{hyperref}
\usepackage{bookmark}
\usepackage{fancyhdr}
\usepackage{longtable}
\usepackage{multirow}
\usepackage{float}
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{microtype}
\usepackage{libertine}
\usepackage{parskip}
\usepackage{environ}
\usepackage{preview}
\usepackage[labelformat=empty]{caption}
\usepackage{amssymb}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{picture}
\usepackage{needspace}
\usepackage{adjustbox}
\usepackage{graphicx}
\pagestyle{fancy}
\raggedbottom
\renewcommand\familydefault{\sfdefault}
\newcommand{\helv}{%
\fontfamily{phv}\fontseries{m}\fontsize{8}{10}\selectfont}
\newcommand{\mycopyright}{\helv Copyright.}
\cfoot{\mycopyright}
\rhead{\textbf{\Sexpr{firstname} \Sexpr{lastname}} \\ \Sexpr{oafr} to \Sexpr{eoafr} \\ Page \thepage}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
\fancypagestyle{fancytitlepage}
{
\fancyhf{}
\cfoot{\mycopyright}
\rhead{}
\renewcommand{\headrulewidth}{0pt}
}
\linespread{1.2}
\usepackage{sectsty}
\allsectionsfont{\sffamily}
\partfont{\centering}
\makeatletter
\newcommand{\sectbox}[1]{%
\noindent\protect\colorbox{gray!40}{%
\#tempdima=\hsize
\advance\#tempdima by-2\fboxsep
\advance\#tempdima by-2\fboxrule
\protect\parbox{\#tempdima}{%
\smallskip
% extra commands here
\centering
#1\smallskip
}}}
\newcommand{\subsectbox}[1]{%
\noindent\protect\colorbox{gray!20}{%
\#tempdima=\hsize
\advance\#tempdima by-2\fboxsep
\advance\#tempdima by-2\fboxrule
\protect\parbox{\#tempdima}{%
\smallskip
% extra commands here
#1\smallskip
}}}
\makeatother
\sectionfont{\sectbox}
\subsubsectionfont{\subsectbox}
\makeatletter
\newcommand\cellwidth{\TX#col#width}
\makeatother
\newlength\foo
\NewEnviron{recipe}{%
\begin{adjustbox}{minipage=\linewidth,gstore totalheight=\foo, gobble}
\BODY
\end{adjustbox}
\needspace{\foo}
\BODY%
}
<<setup, echo=FALSE >>=
opts_chunk$set(fig.path = tempfile(tmpdir="work",pattern=fname))
#
\hyphenpenalty=100000
\begin{document}
\raggedbottom
\setlength{\parskip}{0pt}
<<custom-dev,echo=FALSE>>=
wkld_pdf<-function(file,width,height) {
pdf(file,width=5,height=2)
}
#
<<wkld, echo=FALSE, results='asis',fig.align="center",dev="wkld_pdf",fig.ext="pdf">>=
if (!is.na(wkld.team) | !is.na(wkld.res)) {
g<-pltr$workload.chart(wkld.team,wkld.res,firstname)
print(g)
}
#
\end{document}
In the above example, the file work\fname61c28cd1a0awkld-1.pdf is correctly created, but the tex generated has:
{\centering \includegraphics[width=\maxwidth]{work\fname61c28cd1a0awkld-1}
}
and thus doesn't find it.
It appears that leaving out fileext works (and likely setting it to _pdf would as well) to remove the warning.
It was also necessary to replace the \ generated by tempfile with a / to prevent another warning from the generated includegraphics call, as somewhere in the chain, the \ was evaluated down to . This worked:
opts_chunk$set(fig.path = gsub('\\\\','/',tempfile(tmpdir="work",pattern=fname)))
Thank you for helping me track that down.

How to configure arara to post process .Rnw files in statet / Eclipse

I would like to use arara to post process the .tex files produced from Sweave (.Rnw) documents in R, and use it to build glossaries or bibliographies in reports. How do you integrate that in the statet eclipse plugins ?
The arara header is put on top of the .Rmd file and will be processed to the .tex file as following.
% arara: pdflatex: { action: nonstopmode, synctex: True }
% !arara: bibtex
% arara: makeglossaries
% !arara: pdflatex: {action: nonstopmode, synctex: True }
% !arara: pdflatex: {action: nonstopmode, synctex: True }
\documentclass{article}
\usepackage{glossaries}
\newglossaryentry{salmon}{name={salmon},description={Anadromous migratory fish}}
\newglossaryentry{eel}{name={eel},description={Catadromous fish of the genus
anguilla}}
\makeglossaries
\begin{document}
An example for \gls{salmon} and \gls{eel}
\printglossary[numberedsection]
\end{document}
This way I will be able to run the bibtex and makeglossaries command. Now I want to integrate that command into the statet IDE.
Congigure Arara for eclipse.
Go to the tool button (see below)> external tool configuration
Then click on program > new
And configure arara as following :
Then create an example code. You .Rnw file or latex file must have the first lines with % arara: and commands. Below I'm using first pdflatex to build the file then bibtex and makeglossary, finally I re-run the pdflatex twice for a complete document. You can avoid one step simply by typing !arara:.
Here is an example which uses both \gls{}commands for glossary and \cite{} commands for bibtex. The R code is just to show that this is a .Rnw document.
% arara: pdflatex: { action: nonstopmode, synctex: True }
% arara: bibtex
% arara: makeglossaries
% arara: pdflatex: {action: nonstopmode, synctex: True }
% arara: pdflatex: {action: nonstopmode, synctex: True }
arara.Rnw :
% arara: pdflatex: { action: nonstopmode, synctex: True }
% arara: bibtex
% arara: makeglossaries
% arara: pdflatex: {action: nonstopmode, synctex: True }
% arara: pdflatex: {action: nonstopmode, synctex: True }
\documentclass{article}
\usepackage{glossaries}
\newglossaryentry{knitr}{name={Knitr},description={A package for reproducible
research}}
\newglossaryentry{latex}{name={Latex},description={A typesetting program}}
\newglossaryentry{arara}{name={Arara},description={TeX automation tool based on
rules and directives.}}
\makeglossaries
\begin{document}
<<get_citation, echo=FALSE, eval=FALSE >>=
print(citation("knitr"),bibtex=TRUE)
#
This short reproducible example demonstrates how to use the \gls{arara}
\gls{latex} tool with a \textbf{Sweave} document, using eclipse and \gls{knitr}.
For demonstration we will include a bibliography using \cite{knitr_2017} and
\cite{knitr_2015}.
\printglossary[numberedsection]
\bibliographystyle{plain}
\bibliography{arara}
\end{document}
arara.bib :
#Book{knitr_2015,
title = {Dynamic Documents with {R} and knitr},
author = {Yihui Xie},
publisher = {Chapman and Hall/CRC},
address = {Boca Raton, Florida},
year = {2015},
edition = {2nd},
note = {ISBN 978-1498716963},
url = {https://yihui.name/knitr/},
}
#Manual{knitr_2017,
title = {knitr: A General-Purpose Package for Dynamic Report Generation in R},
author = {Yihui Xie},
year = {2017},
note = {R package version 1.17},
url = {https://yihui.name/knitr/},
}
When first running the .Rmd, the bibliography and glossaries are not built.
So what you do is you shift the the LATEX file and click on the cmd button arara
finally you get the document built with the bibliography and glossaries, re-run the arara process if you need to update the bibliography and glossaries, otherwise just run the knitr command, the pdf will be built.

No author details in pdf, from R-Markdown / LaTeX template

I'm trying to create an R-Markdown template based on the BioMed Central LaTeX template (bmc-article.tex).
The bmc template files are available for download here and needless to say, they work just fine: https://www.biomedcentral.com/authors/tex
In particular, the author, address and note definitions work and produce the desired outcome.
I have replaced the example author, adresse and note definitions in the bmc-article.tex file to use that as a tex template. I have also removed most of the example-content in that file.
The definition examples in the bmc-article.tex, I have replaced with:
$for(author)$
\author[%
addressref={$author.addressref$}, %
$if(author.corref)$corref={$author.corref$}, $endif$ %
$if(author.noteref)$noteref={$author.noteref$}, $endif$ %
email={$author.email$} %
]{\inits{$author.inits$}\fnm{$author.fnm$} \snm{$author.snm$}}
$endfor$
$for(address)$
\address[id=$address.id$]{ %
$if(address.orgname)$ \orgname{$address.orgname$}, $endif$ %
$if(address.street)$ \street{$address.street$}, $endif$ %
$if(address.postcode)$ \postcode{$address.postcode$}, $endif$ %
$if(address.city)$ \city{$address.city$}, $endif$ %
$if(address.cny)$ \cny{$address.cny$}$endif$ %
}
$endfor$
\begin{artnotes}
$for(notes)$
\note[id=$notes.id$]{$notes.text$} % note, connected to author
$endfor$
\end{artnotes}
When 'knitr'ing the Rmd file, it is (as far as I can tell), converted into meningful tex, and I have perused the resulting tex file again and again looking for tex-errors, but find none.
E.g.:
author:
- fnm: "Soren"
snm: "ONeill"
inits: "S"
addressref: "aff1"
email: "sorens mail"
corref: "aff1"
noteref: "n1"
..becomes:
\author[%
addressref={aff1}, %
corref={aff1}, %
noteref={n1}, %
email={sorens mail} %
]{\inits{S}\fnm{Soren} \snm{ONeill}}
The resulting pdf file however is not correct. The superscript numbers which associate names with addresses is displayed as questionmarks and author details at the end of the article is missing altogether.
I fail to see any significant difference between the tex file created by pandoc (based on my Rmd file) and the original bmx template tex file.
The following is rather lengthy I know.
The Rmd example file
title: "Template testing"
author:
- fnm: "Soren"
snm: "ONeill"
inits: "S"
addressref: "aff1"
email: "sorens mail"
corref: "aff1"
noteref: "n1"
- fnm: "Lotte"
snm: "ONeill"
inits: "L"
addressref: "aff2"
email: "lottes mail"
address:
- id: "aff1"
orgname: "University of Southern Denmark"
street: "Campusvej 55"
postcode: "DK 5500"
city: "Odense M"
cny: "Denmark"
- id: "aff2"
orgname: "University of Southern Denmark"
street: "Campusvej 55"
postcode: "DK 5500"
city: "Odense M"
cny: "Denmark"
notes:
- id: "n1"
text: "Equal contributor"
date: "2 jun 2017"
output:
pdf_document:
template: template.tex
keep_tex: TRUE
---
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see rmarkdown.rstudio.com.
This is the template.tex file, which I have adapted from the downloaded bmc-article.tex file
%% BioMed_Central_Tex_Template_v1.06
\documentclass{bmcart}
\usepackage[utf8]{inputenc} %unicode support
\def\includegraphic{}
\def\includegraphics{}
\begin{document}
\begin{frontmatter}
\begin{fmbox}
\dochead{Research}
\title{$title$}
$for(author)$
\author[%
addressref={$author.addressref$}, %
$if(author.corref)$corref={$author.corref$}, $endif$ %
$if(author.noteref)$noteref={$author.noteref$}, $endif$ %
email={$author.email$} %
]{\inits{$author.inits$}\fnm{$author.fnm$} \snm{$author.snm$}}
$endfor$
$for(address)$
\address[id=$address.id$]{ %
$if(address.orgname)$ \orgname{$address.orgname$}, $endif$ %
$if(address.street)$ \street{$address.street$}, $endif$ %
$if(address.postcode)$ \postcode{$address.postcode$}, $endif$ %
$if(address.city)$ \city{$address.city$}, $endif$ %
$if(address.cny)$ \cny{$address.cny$}$endif$ %
}
$endfor$
\begin{artnotes}
$for(notes)$
\note[id=$notes.id$]{$notes.text$} % note, connected to author
$endfor$
\end{artnotes}
\end{fmbox}% comment this for two column layout
\begin{abstractbox}
\begin{abstract} % abstract
\parttitle{First part title} %if any
Text for this section.
\parttitle{Second part title} %if any
Text for this section.
\end{abstract}
\begin{keyword}
\kwd{sample}
\kwd{article}
\kwd{author}
\end{keyword}
\end{abstractbox}
\end{frontmatter}
%$body$
\begin{backmatter}
\section*{Competing interests}
The authors declare that they have no competing interests.
\section*{Author's contributions}
Text for this section \ldots
\section*{Acknowledgements}
Text for this section \ldots
\bibliographystyle{bmc-mathphys} % Style BST file (bmc-mathphys, vancouver, spbasic).
\bibliography{bmc_article} % Bibliography file (usually '*.bib' )
\end{backmatter}
\end{document}
This produces the following tex file (I've instructed RStudio/pandoc to retain the tex file):
%% BioMed_Central_Tex_Template_v1.06
\documentclass{bmcart}
\usepackage[utf8]{inputenc} %unicode support
\def\includegraphic{}
\def\includegraphics{}
\begin{document}
\begin{frontmatter}
\begin{fmbox}
\dochead{Research}
\title{Template testing}
\author[%
addressref={aff1}, %
corref={aff1}, %
noteref={n1}, %
email={sorens mail} %
]{\inits{S}\fnm{Soren} \snm{ONeill}}
\author[%
addressref={aff2}, %
%
%
email={lottes mail} %
]{\inits{L}\fnm{Lotte} \snm{ONeill}}
\address[id=aff1]{ %
\orgname{University of Southern Denmark}, %
\street{Campusvej 55}, %
\postcode{DK 5500}, %
\city{Odense M}, %
\cny{Denmark} %
}
\address[id=aff2]{ %
\orgname{University of Southern Denmark}, %
\street{Campusvej 55}, %
\postcode{DK 5500}, %
\city{Odense M}, %
\cny{Denmark} %
}
\begin{artnotes}
\note[id=n1]{Equal contributor} % note, connected to author
\end{artnotes}
\end{fmbox}% comment this for two column layout
\begin{abstractbox}
\begin{abstract} % abstract
\parttitle{First part title} %if any
Text for this section.
\parttitle{Second part title} %if any
Text for this section.
\end{abstract}
\begin{keyword}
\kwd{sample}
\kwd{article}
\kwd{author}
\end{keyword}
\end{abstractbox}
\end{frontmatter}
%\subsection{R Markdown}\label{r-markdown}
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see rmarkdown.rstudio.com.
\begin{backmatter}
\section*{Competing interests}
The authors declare that they have no competing interests.
\section*{Author's contributions}
Text for this section \ldots
\section*{Acknowledgements}
Text for this section \ldots
\bibliographystyle{bmc-mathphys} % Style BST file (bmc-mathphys, vancouver, spbasic).
\bibliography{bmc_article} % Bibliography file (usually '*.bib' )
\end{backmatter}
\end{document}
The latex log file is rather lengthy (lots of stuff about Unicode char's etc), but this is possibly helpful
LaTeX Warning: Reference `aff1thanks' on page 1 undefined on input line 19.
LaTeX Font Info: Try loading font information for OMS+cmss on input line 19.
LaTeX Font Info: No file OMScmss.fd. on input line 19.
LaTeX Font Warning: Font shape `OMS/cmss/m/n' undefined
(Font) using `OMS/cmsy/m/n' instead
(Font) for symbol `textdagger' on input line 19.
LaTeX Warning: Reference `aff2thanks' on page 1 undefined on input line 25.
\address#aff1=\toks21
\address#aff2=\toks22
LaTeX Font Info: External font `cmex10' loaded for size
(Font) <7> on input line 46.
LaTeX Font Info: External font `cmex10' loaded for size
(Font) <5> on input line 46.
LaTeX Warning: Reference `aff1thanks' on page 1 undefined on input line 46.
No file template_test_1.bbl.
AED: lastpage setting LastPage
LaTeX Font Warning: Font shape `OT1/cmss/m/it' in size <8> not available
(Font) Font shape `OT1/cmss/m/sl' tried instead on input line 89.
Overfull \hbox (1.0pt too wide) has occurred while \output is active
[]
[]
[1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}
] (./template_test_1.aux)
LaTeX Font Warning: Size substitutions with differences
(Font) up to 1.0pt have occurred.
LaTeX Font Warning: Some font shapes were not available, defaults substituted.
LaTeX Warning: There were undefined references.
Of course, I have noticed the warning about "Reference `aff2thanks'", but find no such reference in the original bmx-article.tex
Again, I know this is long -- I apologize for that. I hope someone can make suggestions...

Decreasing space between commands and output in knitr chunks

I'm using knitr with LaTeX and there seems to be a lot of space between the commands echoed by a code chunk and the start of the output:
The LaTeX code for this looks like:
\begin{knitrout}\scriptsize
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{> }\hlstd{lda_test_pred} \hlkwb{<-} \hlkwd{predict}\hlstd{(lda_fit,} \hlkwc{newdata} \hlstd{= seg_test)}
\hlstd{> }\hlkwd{library}\hlstd{(pROC)}
\hlstd{> }
\hlstd{> }\hlstd{lda_roc} \hlkwb{<-} \hlkwd{roc}\hlstd{(}\hlkwc{response} \hlstd{= seg_test}\hlopt{$}\hlstd{Class,}
\hlstd{+ } \hlkwc{predictor} \hlstd{= lda_test_pred}\hlopt{$}\hlstd{posterior[,} \hlstr{"PS"}\hlstd{],}
\hlstd{+ } \hlcom{## we need to tell the function that the _first_ level}
\hlstd{+ } \hlcom{## is our event of interest}
\hlstd{+ } \hlkwc{levels} \hlstd{=} \hlkwd{rev}\hlstd{(}\hlkwd{levels}\hlstd{(seg_test}\hlopt{$}\hlstd{Class)))}
\hlstd{> }\hlstd{lda_roc}
\end{alltt}
\begin{verbatim}
Call:
roc.default(response = seg_test$Class, predictor = lda_test_pred$posterior[, "PS"], levels = rev(levels(seg_test$Class)))
Data: lda_test_pred$posterior[, "PS"] in 346 controls (seg_test$Class WS) < 664 cases (seg_test$Class PS).
Area under the curve: 0.874
\end{verbatim}
\begin{alltt}
\hlstd{> }\hlcom{# plot(exRoc print.thres = .5)}
\end{alltt}
\end{kframe}
\end{knitrout}
The space is generated between the end of alltt and the start of verbatim. Part of the gap, for this example, is the blank line prior to the call output.
Any ideas on how to modulate this in knitr (without affecting any spacing between paragraphs etc)?
Follow the advice found here
control vertical space before and after verbatim environment?
and add the following lines to your document:
\usepackage{etoolbox}
\makeatletter
\preto{\#verbatim}{\topsep=0pt \partopsep=0pt }
\makeatother
For some more detail you can check this answer.

Resources