Load R packages when writing report with Knitr and LaTex - r

I have the below combined systems for writing report with Knitr and LaTeX,
Rstudio Version 0.99.473 with R version 3.2.2
Knitr_1.11
MiKTeX 2.9
Windows 7
An example .Rnw code is shown below, my issue is that a text string "latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase" was created right underneath "Figure 1: Test". I wonder how to get rid of it.
\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}
<<setup, include=FALSE, cache=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before)
library(lattice) else NULL
})
#
\begin{document}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, results='asis', cache=TRUE, fig.show='hold', fig.align='center', warning=FALSE>>=
xyplot(rnorm(100)~rnorm(100))
#
\end{figure}
\end{document}

As the question is not very clearly formulated, and the minimal example is not absolutely "minimal", here a improved version:
Question
Why does the following minimal example add a string like latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase to the output?
\documentclass{article}
<<setup>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before) library(lattice)
})
#
\begin{document}
<<myPackage=TRUE>>=
xyplot(rnorm(100)~rnorm(100))
#
\end{document}
Answer
This has nothing to do with lattice and it's not a special feature of knitr chunk hooks.
What happens?
When a chunk hook returns a character value, this value is included in the output:
In knitr, hooks can also be used to insert texts into the output. To do this, the hook function must return a character result. [knitr: hooks]
In this case, there is no explicit return value of the hook. Therefore, the return value of if() is returned. if() in turn returns the value that library returns:
if returns the value of the expression evaluated, or NULL invisibly if none was (which may happen if there is no else). [see ?"if"]
And finally:
library returns (invisibly) the list of attached packages [see ?libray]
How to avoid it?
First of all, the example is not very good. There's no reason to load a package using a chunk hook. If lattice is required, it should be loaded in the setup chunk.
But there may be cases where a similar chunk hook is useful. Then, the solution is to explicitly return NULL:
knit_hooks$set(myPackage = function(before, options, envir){
if(before) library(lattice)
return(NULL)
})

Here is a minimally changed version that "works for me" (also from RStudio)
\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}
<<setup, include=FALSE, cache=FALSE, echo=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before)
library(lattice) else NULL
})
#
\begin{document}
%\SweaveOpts{concordance=TRUE}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, cache=FALSE, fig.show='hold', fig.align='center', warning=FALSE>>=
print(xyplot(rnorm(100)~rnorm(100)))
#
\end{figure}
\end{document}
I added a echo=FALSE to the first chunk, and removed results='asis' from the second chunk.

Related

Display Block of R Code in Knitr With Evaluation Turned Off

I am writing a document with fairly resource intensive R code. I want to prevent execution of one block of R code in knitr which is giving me document timeout error in Overleaf.
In R studio, this can be done using eval = FALSE. I want to recreate this in knitr. So far, the only way I have found is to suppress errors using <<setup, include=FALSE, cache=FALSE>>= muffleError <- function(x,options) {} but it only works on the entire document.
I specifically want to prevent evaluation but show the R code.
Is this what you want to do, or have I misunderstood? The eval = FALSE is in one code chunk and the second chunk still plots.
---
title: "A Test Knit"
output: html_document
---
## Show code but don't run
```{r, eval = FALSE}
summary(cars)
```
## Run and render plot
```{r}
plot(pressure)
```

call a variable in environnment

I would like to know how to display the result of a variable that is in the environment
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
Hello,
\input{test2.Rnw}
\end{document}
test2.Rnw
\section{test}
<<eval=TRUE, echo=F>>=
paste0("my variable v is worth: ", v)
#
When I compile I get this
You can use the knitr package inside your Rmarkdown code. Check https://riptutorial.com/r/topic/4334/r-in-latex-with-knitr and also this SO Q&A : knitr chunk option eval=TRUE, echo=TRUE, include=FALSE

How to extract a List of Figures from knitr/latex pdf output and load it into R?

Is there an expedient way to extract and load into R a List of Figures that knitr and latex have created in a PDF document?
My PDF has scores of figures; they are sorely in need of being tracked and organized, which the List of Figures helps do. But having the List in R would help in many ways.
Snipping the List from the PDF, pasting it into Excel, and working with that worksheet is one arduous route, but it would be quicker and smoother if it were possible to locate the List of Figures and load it directly (more or less) into R. The knitting process creates many files and perhaps the List lurks within one of them?
Here is a small example simply to create a List of Figures, borrowed from a question on hiding captions here
\documentclass{article}
\usepackage{graphicx}
\setcounter{topnumber}{3}% Just for this example
\begin{document}
\listoffigures
\begin{figure}
\addcontentsline{lof}{figure}{Example image A}%
\centering
\includegraphics[height=4\baselineskip]{example-image-a}
Example image A
\end{figure}
\begin{figure}
\addcontentsline{lof}{figure}{\protect\numberline{}Example image B}%
\centering
\includegraphics[height=4\baselineskip]{example-image-b}
Example image B
\end{figure}
\begin{figure}
\centering
\includegraphics[height=4\baselineskip]{example-image-c}
\caption{Example image C}
\end{figure}
\end{document}
You can do something like this:
---
title: "Untitled"
output:
pdf_document:
fig_caption: true
---
```{r setup, include=FALSE}
gen_lof <- TRUE
if (gen_lof) {
unlink("/tmp/figures.csv")
cat("pdf_name,output_path,caption,subcaption\n",
file="/tmp/figures.csv", append=TRUE)
knitr::knit_hooks$set(plot=function(x, opt) {
cat(x, ",",
opt$fig.path, ",",
opt$fig.cap, ",",
opt$fig.scap, "\n",
sep="", file="/tmp/figures.csv", append=TRUE)
})
}
```
I slightly modified the default RStudio example knitr doc to add two figures with names and captions.
Set gen_lof to FALSE for your normal PDF creation (using a hook mean having to knit once for the full output PDF and once again for just the CSV of figures). Set it to TRUE and knit it to get an list of figures output (wherever you want, I just used that filename for convenience) file that will look like:
pdf_name,output_path,caption,subcaption
Untitled_files/figure-latex/cars-1.pdf,Untitled_files/figure-latex/,lines cars,
Untitled_files/figure-latex/pressure-1.pdf,Untitled_files/figure-latex/,points cars,
While they may have pdf for an output type, it should not be too much trouble to do a 1:1 comparison.
You also have access to all the knitr chunk options this way. i.e.:
aniopts autodep background cache cache.lazy cache.path
cache.rebuild cache.vars child code collapse comment
crop dependson dev dev.args dpi echo engine error eval
external
fig.align fig.cap fig.cur fig.env fig.ext fig.height
fig.keep fig.lp fig.num fig.path fig.pos fig.retina
fig.scap fig.show fig.subcap fig.width
highlight include interval label message out.extra
out.height out.height.px out.width out.width.px
params.src prompt purl ref.label render results
sanitize size split strip.white tidy tidy.opts warning
(I separated out the "fig" specific options on purpose).
The use of a variable to trigger generation means you can code up parameterized knitr workflows to do one gen to get figures and then another to get the final PDF.
Others may have more optimal ways.
As page numbers are not required, it is enough to save fig.cap from each chunk.
This can be done using a chunk hook that saves options$fig.cap in a global variable and saves this variable to a file at the end of the knitting process.
\documentclass{article}
\begin{document}
<<setup>>=
library(knitr)
figureCaptions <- c()
knit_hooks$set(listit = function(before, options, envir) {
if (!before) figureCaptions <<- c(figureCaptions, options$fig.cap)
})
<<fig.cap = "First one", listit = TRUE>>=
plot(1)
#
<<fig.cap = "Second one", listit = TRUE>>=
plot(rnorm(10))
#
<<final>>=
save(figureCaptions, file = "figureCaptions.RData")
#
\end{document}
It should be better to save the caption only after the chunk has been evaluated (if (!before)) in order to avoid problems with eval.after.
To access the captions afterwards, use load("figureCaptions.RData").

Show only selected figures of generated figures in a cache in knitr

If I have a chunk that generates 4 figures and I want to keep them all (fig.keep=all), is it possible to show only the second one using a cache option? I see that echo=2:5 can be selected, but it doesn't seem that fig.show=2 is possible. Is the best method to do \includegraphcis{fig2.pdf}?
Thanks.
If you don't want to keep all figures you can simply use :
Use argument fig.keep=c(2,4)
Reproducible example :
\documentclass[a4paper]{article}
\begin{document}
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr)
#
<<multiplefig, fig.keep=c(2,4),fig.height=4,fig.with=10, out.width='.8\\linewidth'>>=
mapply(function(X)plot(X,main=X),c(1:4))
#
\end{document}
However, since you want to keep figures, I would do it the old way in sweave, save the figures using png or pdf.
Reproducible example :
\documentclass[a4paper]{article}
\usepackage{graphicx}
\graphicspath{{figure/}}
\begin{document}
<<multiplefig, echo=FALSE>>=
for (i in 1:4){
png(file=paste0(getwd(),"/figure/fig",i,".png"))
plot(1,1,main=i,cex.main=4)
dev.off()
}
#
This plot shows only figure \ref{fig:fig2} but 4 other are saved
\begin{figure}[htbp]
\centering
\includegraphics[width=0.5\textwidth]{fig2.png}
\caption{}
\label{fig:fig2}
\end{figure}
\end{document}

Displaying <<..>>= in output

I want demonstrate a sample piece of R code WITH the knitr <<..>>= preamble in a LaTeX document. Here is an example of the output I desire:
It's got to be simple - but I'm missing something. I checked the documentation and scanned stack overflow - but without luck. Here is a MWE:
\documentclass{article}
\begin{document}
<<mychunk, cache=TRUE, eval=FALSE, dpi=100>>=
"hello world"
#
\end{document}
Suggestions? I tried indenting the code in LaTex and wrapping in a verbatim block, but only got errors.
I just checked the manual of knitr. This is how the package author solved the problem:
<<use-ext-chunk, echo=FALSE, comment=NA>>=
cat('<<Q1, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
#
which produces the output as shown on page 9 of the knitr manual
Here is a minimal example:
\documentclass[a4paper]{article}
\begin{document}
<<use-ext-chunk, echo=FALSE, comment=NA>>=
cat('<<Q1, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
#
\end{document}
which produces the attached output.
I had the same question on tex.stackexchange.com a year ago and got a few nice responses: https://tex.stackexchange.com/q/35485/3419. This is for Sweave but I think it will work the same in knitr.
I think I ended up just using \Sexpr{"<<>>="} and \Sexpr{"#"} in verbatim environment. e.g.:
\documentclass{article}
\begin{document}
\begin{verbatim}
\Sexpr{"<<mychunk, cache=TRUE, eval=FALSE, dpi=100>>="}
"hello world"
\Sexpr{"#"}
\end{verbatim}
\end{document}
Just a quick follow-up: this feature has been implemented in knitr (devel version >= 0.8.15); see examples for both Rnw and Rmd. An alternative solution is in knitr FAQ.

Resources