Easy Sweave for LaTeX and R

When you’re writing up reports using statistics from R, it can be tiresome to constantly copy and paste results from the R Console. To get around this, many of us use Sweave, which allows us to embed R code in LaTeX files. Sweave is an R function that converts R code to LaTeX, a document typesetting language. This enables accurate, shareable analyses as well as high-resolution graphs that are publication quality.

Needless to say, the marriage of statistics with documents makes writing up APA-style reports a bit easier, especially with Brian Beitzel’s amazing apa6 class for LaTeX.

Making Sweave Available Systemwide

However, Sweave doesn’t always work correctly. One common complaint that you’ll get after Sweaving a file is Sweave.sty not found!. While Sweave.sty is a LaTeX package, it doesn’t live with the rest of the LaTeX packages because it’s installed using R. Many people try to solve this by copying and pasting Sweave.sty into every document directory, but I’m sharing a better way below.

Using Terminal.app:

If using mktexlsr results in a command not found error, the TeX Live distribution probably isn’t in your \$PATH, but you can hunt for the program anyway. For example, if you’re using MacTeX 2013, the program will be found in a directory similar to this:

Using Sweave in TeXShop

When you’re getting started with LaTeX, many Mac users prefer the bundled editor, TeXShop. Cameron Bracken gives us a helpful piece of code that allows easy Sweaving straight from TeXShop. TeXShop uses various engines that allow it to render LaTeX. Using a bit of BASH scripting, we can write our own Sweave engine and make it available right within TeXShop. I have adapted Cameron’s original engine to accomodate Bibtex citations (see here).

Using a text editor, paste in the following syntax and save the file as Sweave.engine:

Next, in Terminal.app, move the file to the TeXShop engines folder:

Now restart TeXShop if it’s running and you should see Sweave as an available option!