R, Sweave: How to pass file encoding to patchDVI::SweavePDF? - r

I have a master file master.tex containing the preamble and which inputs (via
\input{chapter01}, \input{chapter02}, ...) chapters. The chapters are .Rnw
files. My goal is to use patchDVI::SweavePDF to compile the chapters (say,
chapter.Rnw) individually (each chapter starts with sourcing Sweave preliminary
settings but [of course] does not have a preamble). When I execute
Rscript -e "patchDVI::SweavePDF('chapter.Rnw')
I obtain
Error: ‘chapter.Rnw’ is not ASCII and does not declare an encoding
Normally one uses \usepackage[utf8]{inputenc} to solve this problem. However, I
can't put this into chapter.Rnw since it is only allowed in the preamble, so in
master.tex. But there it has no effect. The question is how to solve this.
I found this but I couldn't figure out how to adjust it to make it work with patchDVI::SweavePDF.

Related

Using graphicspath in latex/sweave

I have an Sweave file, where I need to embed a png and pdf from another folder. This is how I tried it
\usepackage{graphicx}
\graphicspath{{inst/extdata/}}
\DeclareGraphicsExtensions{.pdf,.png}
\begin{document}
\begin{figure}
\includegraphics[scale=0.7]{image.png}
\caption{captionA}
\label{fig:labelA}
\end{figure}
I also tried like this, but this didn't work:
\graphicspath{{filePath}}
filePath = "C:/path"
\begin{figure}
\includegraphics[scale=0.7]{image.png}
\caption{captionA}
\label{fig:labelA}
\end{figure}
I have googled a lot, and look up https://en.wikibooks.org/wiki/LaTeX/Importing_Graphics#Compiling_with_latex, but this is the error I get.
LaTeX Warning: File `image.png' not found on input
line 613.
! Package pdftex.def Error: File `image.png' not found.
See the pdftex.def package documentation for explanation.
Type H <return> for immediate help.
...
l.613 ...]{image.png}
I expand my comment with three different ways of achieve your goal; Suppose you want to include a file image named IMG_7254.JPG (note that I do not write the file extension in the following code because I use the \DeclareGraphicsExtensions{.JPG}), You can do it in three ways:
to put the file to compile (the .tex one) and the image to include in the same folder. LaTeX searches (by default) for pictures to include in documents in the same directory where the file to be compiled is. In this case the code is just:
\includegraphics[width=0.7\textwidth]{IMG_7254}
Have pictures and file to compile in very different folders, in this case you must specify the complete path of the file (it can be found in different ways), example with Mac OS read here. In this case the code is:
\includegraphics[width=0.7\textwidth]{/Users/SabDeM/Pictures/IMG_7254}
to put the file to compile in a folder (say File_to_com), then put all pictures to include in a sub folder, say, File_to_com/picturesToInc, and then specify the path. In this latter case the code is:
\includegraphics[width=0.7\textwidth]{picturesToInc/IMG_7254}
As you can see in all ways (one way or another) LaTeX (which render the PDF) must to know where the pictures are located in your computer.

Long documents on R Sweave include files

I'm writing a book in R Sweave, as long as the document is becoming larger I use the \include LaTeX command to include files. When I PDF-Compile the main file the files with R chunks are not included. What extension they must have .tex or .Rnw?
From the Sweave User Manual, p. 7
Latex files can include others via \input{} commands. These can
also be used in Sweave files, but the included files will be included by
Latex and are not processed by Sweave. The equivalent if you want
the included files to be processed is the \SweaveInput{} command.
Included files should use the same Sweave syntax (see below) and
encoding as the main file.

Latex and Sweave, cannot include figure

I have a file for my thesis, which include the chapters.
A few weeks ago, I worked with R-Statistic and *.rnw files to produce a *.tex paper.
Now, I want to include these *.tex paper in my thesis. However, every time I get several errors.
Structure
/home/UserName/R-files/Dokumentation5.rnw
/home/UserName/tex-Files/Dokumentation5.tex // from Dokumentation5.rnw files
In the following folder, I put the TeX and the figures (*.pdf).
/home/UserName/Documentation/chapter/
Edit the Dokumentation5.tex, remove the beginning and "end document"
In thesis file, I added the following commands:
\usepackage{Sweave} \include /home/UserName/Documentation/chapter/
run latex
If I run LaTeX, I got several errors like:
File `Dokumentation5-004' not found.
\begin{document} ended by \end{Schunk}.
Too many }'s
File `Dokumentation5-033' not found.
Create a file master.Rnw that contains nothing but the LaTeX setup (packages to be used, geometry, title, begin/end document, bibliography style and file......)
If you need to use R functions in various places in your paper, create a file func.Rnw where you create these functions. Make this file the first to \SweaveInput{func.Rnw} in your master.Rnw - see here for details
Now create one file for each "unit" of your paper (chapter, section, whatever you like). Make them all chapX.Rnw files, whether they contain R code or not.
\SweaveInput{chapX.Rnw} them in the desired order in your master.Rnw file.
At any time during the process, run Sweave("master.Rnw") in R and then pdflatex master.tex from the console to see what you have produced.

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.

practically getting started with Sweave

my question(s) might be less general than the title suggests. I am running R on Mac OS X with a MySQL database to store the data. I have been working with the Komodo / Sciviews-R for some time. Recently I had the need for auto-generated reports and looked into Sweave. I guess StatET / Eclipse appears to be the "standard" solution for Sweavers.
1) Is it reasonable to switch from Komodo to StatET Eclipse? I tried StatET before but chose Komodo over StatET because I liked the calltip / autosuggest and the more convenient config from Komodo so much.
2) What´s a reasonable workflow to generate Sweave files? Usually I develop my R code first and then care about the report later. I just learned today that there is one file in Sweave that contains R code and Latex code at once and that from this file the .tex document is created. While the example files look handily and can't really imagine how to enter my 250 + lines of R code to a file and mixed it up with Latex.
Is it possible to just enter the qplot() and ggplot() statements to a such a document and source the functionality like database connection and intermediate results somehow?
Or is it just a matter of being used to the mix of Latex and R code?
Thx for any suggestions, hints, links and back-to-the-roots-shout-outs…
You've asked several questions, so here's several answers;
Is StatEt/Eclipse the right way to do Sweave ?
Not nessarily (note: I'm an avid StatEt/Eclipse user, and use it for both pure R and Sweave/R and love it, I haven't used Komodo / sciviews-R). You should be able to run the sweave command from any R command line which will generate a .tex file. You can then turn the .tex file into something readable (like pdf) from any tex environment.
What's a good Sweave workflow ?
When I have wanted to turn an r script into a sweave report I generaly start with an empty sweave template and copy/paste my entire R script into a sweave R block just after the title, i.e;
<<label=myEntireRScript, echo=false, include=false>>
#Insert code here
myTable<-dataframe(...)
myPlot<-qplot(....)
#
Then I go through and find the parts I want to report. For instance, if i want to put a table into the report, I'll cut the R block and put an xtable block in, and the same for variables and plots.
<<label=myEntireRScript, echo=false, include=false>>=
#Insert code here
#
Put any text I want before my table here, maybe with a \Sexpr{print(variable)} named variable
<<label=myTable, result=Tex>>=
myTable<-dataframe(...)
print(xtable(mytable,...),...)
#
Any text I want before my figure
<label=myplot, result=figure>>=
myPlot<-qplot(....)
print(qplot)
#
You may want to look at these related SO posts. The rest of my post relates to your question 2.
When creating reports with Sweave, I usually keep most of the R code and the report text separate. If the R code is fast to run, then I prefer I will include something like the following at the start of the .Rnw file:
<<>>
source('/path/to/script.r')
#
On the other hand, if the R code takes a long time, I will often include something like the following at the end of the R script:
Sweave('/path/to/report.Rnw'); system('pdflatex report.tex')
That way, I can re-generate the report quickly, without needing to run all the R code again. Then, the only work R has to do in the Sweave file is print tables, make graphs and maybe extract a few figures.
Like nullglob, I prefer to keep the R and Sweave files separate, but I prefer to save the workspace with save.image() rather than to source() the file. This avoids running the R calculations with each .Rnw file compiling (and I always end up tinkering with the typesetting more than I'd like).
My general work flow is to do each paper/project in it's own folder with it's own R file(s). When the calculation side is "done", I save.image() to store all the workspace variables as-is.
Then, in the .Rnw file in the same directory I set the working directory with setwd() and load all variables with load(".Rdata"). Of course, you can change the name you use for your workspace, but I do one workspace per folder and keep the default name. Oh, and if you tinker with the R file, be sure save the workspace image and watch out for variables that linger in the workspace and .Rnw file, but are no longer part of the R file... this is where the save.image() approach can cause some headaches.
I am on a Mac and I suggest TextMate if you're mildly geeky and emacs/ess if you're really geeky. I use vim and command line R, but emacs/ess works best for most. If you're in this for the long haul, I doubt you'll regret learning emacs/ess for R, Sweave, and LaTeX.

Resources