Keep auxiliary TeX files when rendering a rmarkdown document - r

I am rendering two documents, that cross-reference items in each other. For that I am using the LaTeX package zref.
To make zref work, it needs the *.aux file of the documents which are created when calling pdflatex.
Unfortunately, using RStudio and its basic approach to render the document (the knit button, Cmd+Shift+K or rmarkdown::render()) these files will be deleted after the compilation was successful.
Unchecking the global option Tools -> Global Options -> Sweave -> Clean auxiliary output after compile does not help.
I know of two options to go around this:
Manually compile the tex file after the pdf was rendered.
Write a makefile that does that.
But is there another option I am not aware of?

rmarkdown::render() eventually calls tinytex::latexmk() to compile the intermediate .tex to .pdf. To preserve auxiliary files, you need tinytex::latexmk(..., clean = FALSE). One way to set clean = FALSE is through the global option options(tinytex.clean = FALSE). You can set this in either your .Rprofile or a code chunk of your Rmd document.
The RStudio option you mentioned is only for Sweave documents (.Rnw).

Related

Execute all R chunks of an external Rmd file from an R script

I have a .Rmd file called f1.Rmd (containing a mix of text and R chunks) and an R script called f2.R.
I would like to insert a set of R instructions in f2.R that would execute all the R chunks contained in f1.Rmd, in such a way that all variables created in f1.Rmd would be created in my current R session if I source f2.R
(similarly to what happens when clicking on "Run" -> "Run all chunks below from the Rstudio menu").
If you render the f1.Rmd file from your current environment, this should happen.
You can use rmarkdown::render() from the console or a .R script. This will create all the variables in your current environment. It will also have the side effect of making the document.
When you use the knit button in RStudio, this launches the render in a new r session as a background process.
See also the envir option for render.
See also this answer for other options. knitr: run all chunks in an Rmarkdown document
It also depends what your .Rmd is doing.

Adding XeTeX to ess-swv-PDF

I am working with an .Rnw file with Hebrew in it, and I would like to compile the resulting .tex file using XeTeX. I work in Emacs, so I am using the Emacs Speaks Statistics (ESS) package, which allows a few options for compiling the .tex file. However, using XeTeX is not currently among the possible selections of ess-swv-PDF, accessed via M-n P.
I would like to add XeTeX to this list. Ideally, this added option would allow me to not only compile the .tex file using XeTeX but also run, as needed, BibTeX on the same file—all from a buffer displaying the .Rnw file. This would be similar to texi2pdf, one of the current options of ess-swv-PDF.
This can be customized if you have ESS already installed: M-x customize-group select ess-sweave and edit ess-swv-pdflatex-commands to add "xelatex" to them. If you want to use xelatex or xetex as the default TeX engine, like I do, you can put that in front (see screenshot below).
Then press Apply and save this should save code into your .init.el or .emacs.el, depending on your setting.
Now when you go to your .Rnw file and hit M-n P you will see xelatex as default since you put it ahead of other commands. That is all to it.

knitr: Document does not change anymore

I have a .Rnw document in which I include childs. The childs produce tables via the 'latex' command of the Hmisc library in R.
When I make changes in the child documents, these changes do not anymore change the pdf document. My first guess was to use the chunk option 'eval=TRUE', but this does not change anything. Then, I saw, that the tables are actually saved to a .tex file with same name as the .Rnw document. I deleted this file and after compilation with knitr I got an error:
Error: Latexmk: Could not find file documentname.tex.
I assume, this is not the way to do it. Now I am out of ideas what to do. I appreciate some help on my problem.
Best
Simon
Allright, when trying to construct a simple example, I actually found out, that neither the packages I included nor the nesting of child documents interfere with the compilation via knitr. The reason was a simple error in the low-level .Rnw document, where a Hmisc latex table had a label, that missed a closing speech mark.
This causes then the output pdf not to change - I assume, that in this case the already constructed .tex file is included instead of letting knitr recompile the .Rnw documents and this hasn't changed since the last compilation?
What I wonder about is the different format of the landscape ctable in the document. Using a simple knitr document just with \documentclass{article} produces well placed tables. In my document using a template for the JFE, I get a table that extends over the whole page and even in footnotesize it is far away from the great appearance in the simple document. There is only a margin of less than half a cm on the right and the left. Page size is the same: both US letter... Can I probably control that via knitr or only via resizebox?

How to convert R Markdown to HTML? I.e., What does "Knit HTML" do in Rstudio 0.96?

What commands are run when pressing "Knit HTML" on an R Markdown file in Rstudio 0.96?
My motivation is that I might want to run the same command when I'm in another text editing environment or I might want to combine the command in a larger makefile.
Basic Script
So now that the R markdown package has been released, here is some code to replicate the features of Knit to Html.
require(knitr) # required for knitting from rmd to md
require(markdown) # required for md to html
knit('test.rmd', 'test.md') # creates md file
markdownToHTML('test.md', 'test.html') # creates html file
browseURL(paste('file://', file.path(getwd(),'test.html'), sep='')) # open file in browser
where test.rmd is the name of your R markdown file.
Note that I'm not 100% confident about the browseURL line (hence my question here about opening files in a web browser).
markdownToHTML Options
The good thing about markdownToHTML is that there are heaps of options in how the HTML is created (see ?markdownHTMLOptions). So for example, if you want just a code fragment without all the header information, you could write:
markdownToHTML('test.md', 'test.html', options='fragment_only')
or if you don't like hard wrapping (i.e., inserting line breaks when there are single manual line breaks in the markdown source), you can omit the 'hard_wrap' option.
# The default options are 'hard_wrap', 'use_xhtml',
# 'smartypants', and 'base64_images'.
markdownToHTML('test.md', 'test.html',
options=c('use_xhtml', 'base64_images'))
Makefile
This could also all be added to a makefile perhaps using Rscript -e (e.g., something like this). Here's a basic example makefile I put together, where test indicates that the rmd file is called test.rmd.
RMDFILE=test
html :
Rscript -e "require(knitr); require(markdown); knit('$(RMDFILE).rmd', '$(RMDFILE).md'); markdownToHTML('$(RMDFILE).md', '$(RMDFILE).html', options=c('use_xhtml', 'base64_images')); browseURL(paste('file://', file.path(getwd(),'$(RMDFILE).html'), sep=''))"
The makefile uses my preferred markdown options: i.e., options=c('use_xhtml', 'base64_images')
Put Sys.sleep(30) in a chunk and you will see clearly what commands are called by RStudio. Basically they are
library(knitr); knit() to get the markdown file;
RStudio has internal functions to convert markdown to HTML;
The second step will be more transparent in the next version of the markdown package. Currently you can use knitr::knit2html('your_file.Rmd') to get a similar HTML file as RStudio gives you.
Update on 2019/09/17: The above answer applies to RStudio v0.96 (in the year 2012). Now R Markdown is compiled through rmarkdown::render(), which uses Pandoc instead of the retired R package markdown. See the post Relationship between R Markdown, Knitr, Pandoc, and Bookdown for more details.
Very easy command line method from knitr in a knutshell:
R -e "rmarkdown::render('knitr_example.Rmd')"
This requires rmarkdown to be installed with install.packages(rmarkdown) and that pandoc is installed (apparently it comes with Rstudio, see knitr in a knutshell for more details).
So far when I've used this it nicely puts all the plots in the HTML file rather than as images in a figure directory and cleans up any intermediate files, if any; just like compilation in RStudio does.
It seems you should call rmarkdown::render() instead of knitr::knit2html() because a.rmd appears to be an R Markdown v2 document.

How do I Sweave a multiple-file project?

I am writing my thesis in LaTeX and because things got a bit long for my taste, I had split it into several files. Let's call them thesis.tex, intro.tex, mat_n_met.tex, rslts.tex and discsn.tex. I have linked intro.tex, mat_n_met.tex, rslts.tex and discsn.tex through thesis.tex with \include{intro} (and so on...).
I have also created a separate file called r_crunching.Rnw (that I run through Sweave) that holds a chunk that runs the R script with data analysis and chunks that produce pdf outputs of graphs that I embed via \includegraphics (in e.g., rslts.tex). Still following?
If I run a Rnw (i.e. I renamed rslts.tex to rslts.Rnw) without "a link" to the chunk with the R script, you will get a Sweave() error saying the reference in \Sexpr{} doesn't exist. Is there a way, without merging all the files into a single .Rnw, to call \Sexpr{} in say rslts.Rnw?
Other methods how to accomplish this are welcome.
I recommend using RStudio (http://www.rstudio.com/ide/). Sweave is nicely integrated into that IDE and it supports multi-file documents. Even Synctex and TeX error log navigation still work when working with multi-file documents.
From the master file you can include child files using
\SweaveInput{Child.Rnw}
You can link a child file back to the master file by including the directive
% !Rnw root = Master.Rnw
in the child file. That way when working on a child file and typesetting it, RStudio know to typeset the master file.
The details are explained in the RStudio documentation at http://www.rstudio.com/ide/docs/authoring/multiple_rnw_files
Forget for a second that you are dealing with Sweave and just think of the latex problem -- for which \include and \includeonly offer solutions. Try that with a few simple test files.
Once you have that figured out, fold Sweave back into the mix and it just work as Sweave is after 'merely' a pre-processing step, albeit a very clever one.
To expand Dirk's and mjm's answer, I would suggest using \include's and Makefiles.
Suppose you have a master file: master.tex. In that file, you include some .tex and .Rnw files, i.e.
\include chapter1
\include chapter2
\include chapter3
....
Now the following Makefile provides functions for creating the .tex, .R and .pdf files:
.SUFFIXES: .tex .pdf .Rnw .R
MAIN = master
##List your your .Rnw includes
RNWINCLUDES = chapter1 chapter2 chapter3
TEX = $(RNWINCLUDES:=.tex)
RFILES = $(RNWINCLUDES:=.R)
RNWFILES = $(INCLUDES:=.Rnw)
all: $(MAIN).pdf
$(MAIN).pdf: $(TEX) $(MAIN).tex
R: $(RFILES)
.Rnw.R:
R CMD Stangle $<
.Rnw.tex:
R CMD Sweave $<
.tex.pdf:
pdflatex $<
bibtex $*
pdflatex $<
pdflatex $<
Essentially, the .SUFFIXES provide a set of rules for convert from one file format to another. For example, to convert from .Rnw to .R, we use the command
`R CMD Stangle $<`
one fairly obvious answer is to use a makefile, possibly using package cachesweave, to process the relevant files in the right order.
My solution to multi-file projects in Sweave (under Rstudio) is the following:
1) Create a master file, say master.Rnw, in which you have the calls to the subfiles intro.Rnw, matmet.Rnw, etc:
\documentclass[11pt]{book}
% \usepackage{blah, blah} as you wish
\graphicspath{ {./figs/}
\begin{document}
\SweaveOpts{concordance=TRUE}
\include{intro} % a call to 'intro.Rnw'
\include{matmet} % a call to 'matmet.Rnw'
\include{results} % a call to 'results.Rnw'
\include{discuss} % a call to 'discuss.Rnw'
\end{document}
2) Create the subfiles. I'm giving here only the first one, intro.Rnw. Please note that in the subfiles you do not use preambular commands such as \documentclass or \begin{document}
\chapter{Introduction}\label{ch:intro}
\section{This is section 01}
In section 01 we are concerned about whether \texttt{Sexpr} could possibly work. The chunk below creates a variable \em{a} which will be referred to by this command later on.
<<>>=
a <- 1+2
#
Ok, if it is working, we shall see number 3 right here: \Sexpr{a}.
3) After saving modifications in 'intro.Rnw', simply go to 'master.Rnw' and compile it using Ctrl+Shift+K and... voilá:
Screenshot of the file created by the above command.

Resources