Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sweave: interpret R's output as LaTeX code

Tags:

r

latex

sweave

I have written some custom R code that wraps a third-party binary. One of that binary's features is to produce a LaTeX document with a figure and some text. One of my code's features is to parse that document and return the LaTeX code for the figure.

The goal is to embed my R code in an Rnw document. When Sweave is run, I want my code to produce a document using the third-party binary, then extract the LaTeX code for the figure and drop it into Sweave's .tex output. Then when I run latex against that output the figure that was generated by the third-party binary should appear, automagically and nicely formatted, in my report.

Instead, the LaTeX code is printed out like this:

[1] " %\\begin{landscape}"
[1] " \\begin{center}"
[1] "\\psset{linecolor=black,tnsep=2pt,tnheight=0cm,treesep=.3cm,levelsep=40pt,radius[1] "% \\def\\psedge#1#2{\\ncangle{#2}{#1}}"
[1] "% \\pstree[treemode=R]"
[1] " \\pstree{\\Tcircle{ 1 }~[tnpos=l]{\\shortstack[r]{nwsprec\\\\$\\leq$ 1.93}}}{"

And so on...

Is there a way to make Sweave treat R's output as LaTeX code?

Thanks in advance. -Wesley

like image 609
Wesley Avatar asked Jun 14 '11 22:06

Wesley


People also ask

How do you Sweave in R studio?

To start a new Sweave document, go to File | New and select "R Sweave". This will provide a basic Sweave template. From here, you can enter text and LaTeX commands. R chunks can also be inserted to interweave R commands and output into your document.

Can you write LaTeX in R?

If that is the case, my favourite solution is the R package “knitr” that allows us to create LaTeX documents directly from R code. Combining the flexibility of a programming language and the LaTeX aesthetics. In this article, I want to give you a basic tutorial and some tips on how to do it successfully.

What is a Sweave document?

Abstract Sweave is a tool that allows to embed R code in LATEX documents. The code can be evaluated and the resulting console output, figures and tables are automatically inserted into the final document.


1 Answers

I figured it out! The Sweave code needs to look like this:

<<echo=False, results=tex, include=True>>=
...R code goes here...
@

Where the option results=tex is the crucial change that tells Sweave to interpret the output from R as LaTeX code.

And to get rid of the quotes and line numbers, I needed to use cat command in R rather than print. Specifically, I changed print(line) to cat( paste(line, "\n", sep='') ).

like image 98
Wesley Avatar answered Sep 27 '22 21:09

Wesley