# Sweave Setup

The ability to incorporate R code alongside Latex equations is one of the great advantages of using RStudio. But as a coding program, RStudio does not have any text completion for Latex and does a poor job at explaining Latex errors. This can make writing Latex inside RStudio frustrating and it is often much easier to simply open Texmaker and copy and paste Latex code into RStudio. However, this can also be difficult if you are trying to make changes to your Latex later and requires you to move between several open windows.

I’ll also cover some ways to automatically load default packages, both by changing the default packages loaded in RStudio and by adding an external preamble file. Specifically:

PS: I think that your are accessing this page on a and have automatically hidden instructions for other operating systems from you below. Change this drop-down menu to see instructions for other operating systems.

## Syncing files from Rstudio/Texmaker

The easiest step is allow RStudio and Texmaker to open the same file simultaneously. By default, if you try to open an .Rmd file in Texmaker that is already open in RStudio, it will complain that the file is already open. But if we allow Texmaker to look for external changes, then it can simply update the file it has open when other applications edit it. This avoids you needing some sort of scratch paper Texmaker application open and allows you to add Latex code directly into your RStudio application.

In Texmaker, go to Preferences/Options/Editor/Check for External Changes and enable it. Now it will prompt you to reopen a file if another application has saved a newer version. RStudio automatically checks for external changes so there’s nothing we have to change there.

If you run into errors, try adding \usepackages{Sweave} to the Latex preamble.

## Setting up Sweave in TexMaker

The shortcoming of the solution above is that Texmaker can’t actually compile the .Rmd file so while you can write your Latex code through Texmaker directly onto the .Rmd file, you have to switch back into RStudio to have it compile, and RStudio does not give the most helpful error messages if it runs into a problem with the Latex code.

But we can get around this is we set up Texmaker to compile R code as well. After completing these steps, you’ll be able to add equations into Sweave files, and compile along the way to check for errors, all without leaving Texmaker.

For a PC using knitr, following the following steps:

Go to User/User Commands/Edit User Commands.

Name the menu item knitr and paste the following code, updating the file paths to your R directory and your Adobe Reader. The pipe operator is applying new terminal commands to the output of the previous command.

"C:\Program Files\R\R-3.2.3\bin\x64\Rscript.exe" -e "knitr::knit2pdf('%.Rnw')" | pdflatex -synctex=1 -interaction=nonstopmode %.tex|"C:/Program Files/Adobe/Reader 11.0/Reader/AcroRd32.exe" %.pdf

Be sure to add library(knitr) to your R preamble, especially if you’re using any of the knitr commands like opt_chunks$set. Now you can change one of your execution commands in the option bar to your custom knitr command. For a Mac using knitr, Texmaker ships out with an option to compile Sweave documents already. If you open Preferences, you’ll find the code to compile a Sweave document. The default command executes the following code: R CMD Sweave %.Rnw But knitr is much more powerful and you should use it instead. You can run knitr by changing the code in that box to the following: /Library/Frameworks/R.framework/Resources/Rscript -e "knitr::knit2pdf('%.Rnw')" But the downside is that this just compiles the document into a .tex document, it doesn’t also compile the tex document into a pdf. So we’re going to string a couple of commands together to form a custom command that we can add to the menu bar. Go to User/User Commands/Edit User Commands. Name the menu item knitr and paste the following code. The pipe operator is applying new terminal commands to the output of the previous command. /Library/Frameworks/R.framework/Resources/Rscript -e "knitr::knit2pdf('%.Rnw')"|"pdflatex" -synctex=1 -interaction=nonstopmode %.tex|open %.pdf You can recreate these steps yourself by choosing the wizard option in the Edit User Commands dialogue and selecting the following elements: R Sweave, pdflatex, pdfViewer. This only works for knitr if you updated the R Sweave command in the preferences above. Be sure to add library(knitr) to your R preamble, especially if you’re using any of the knitr commands like opt_chunks$set.

Now you can change one of your execution commands in the option bar to your custom knitr command.

It seems to be a little bit slower to compile the R code from within Texmaker than within RStudio, so this is a bit of a cost.

If you’re working with a Latex document, its also very easy to load an external file as your preamble which specifies all of your packages. For example, below you see the heading of my class notes, which is very clean and sparse. All of the package loading is happening in the preamble file, which is below.

Here are the notes:

\documentclass[11pt,a4paper]{article}
\input{/Users/Vincent/Desktop/preamble.tex}

% \setcounter{secnumdepth}{-2} %removes numbering from sections so they will still appear in the TOC

\title{450D: Bayesian Statistics Notes}
\author{Vincent Bauer}
\date{02/10/2017}

\begin{document}

\maketitle
\tableofcontents

And here’s the preamble:


%Latex Preamble
%Vincent Bauer
%1/15/2017

%access using
%\documentclass[11pt,a4paper]{article}
%\input{/Users/Vincent/Desktop/preamble.tex}
%I would include the document class in the preamable but
%knitr needs to have the document class specified before inputting

%formatting
\usepackage[margin=1in]{geometry} %margins
\setlength\parindent{0pt} %no paragraph indenting
\usepackage[utf8]{inputenc}  %not sure why I need this

%math packages
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{calrsfs}  %make mathcal swirly
\usepackage{bm} %bold math

\newcommand{\E}{\mathbb{E}}
\renewcommand{\L}{\mathcal{L}}
\DeclareMathOperator*{\Cov}{Cov}
\DeclareMathOperator*{\indp}{\perp\!\!\!\perp}
\DeclareMathOperator*{\Var}{Var}

%other packages
\usepackage{graphicx}  %inserting images
\graphicspath{ {img/} }  %graphics path
\usepackage{float}  %figure float
\usepackage{soul}   %underlining
\usepackage{xcolor}  %color
\usepackage{setspace} %line spacing


You can use the same preamble code in Sweave, but there are some conflicts between knitr and xcolor. You fix them by adding this code chunk

<<>>=
library(knitr)

knit_hooks\$set(document = function(x) {sub('\\usepackage[]{color}', '\\usepackage{xcolor}', x, fixed = TRUE)})
@


## Changing the Sweave/RMarkdown template

I found myself copying and pasting the same preamble into most of my documents in order to load some of the most useful R functions and set several knitr options. To avoid wasting time copying and pasting from older documnts, I found out how to change the default documents loaded for .Rnw and .Rmd files. This is especially helpful when combined with the preamble I made above, which

For a PC, navigate to C:\Program Files\RStudio\resources\templates where you’ll find sweave.Rnw and r_markdown.Rmd templates that you can open and change. The one complication is that it won’t let you save any changes until you set the permissions.

1. Right click the templates folder, Properties
For a Mac, find the RStudio package in your Applications package, command/right click, and select “Show Package Contents”, then navigate to Contents/Resources/resources/templates a where you’ll find sweave.Rnw and r_markdown.Rmd templates that you can open and change.