How to capture R text+image output into one file (html, doc, pdf etc)?

Tal Galili picture Tal Galili · Sep 28, 2010 · Viewed 17.2k times · Source

The task is to create a file (word, rtf, pdf, html, or whatever) that will capture the output of R (e.g: not the code that created the output), into that format (including text and images).

The way of doing this should involve as little change to the original R script as possible.

If I had cared only for the text or images, then I would use ?sink, or ?pdf. But I don't know how to combine the two into one output in an easy way.

I know there is a way to export R output using r2wd, but it involves too much medaling in the original code for my taste (I imagine the same is true for the sweave solution, although I don't have experience with it to tell)

Here is a sample code for future examples:

START.text.and.image.recording("output.file") # this is the function I am looking for
x <- rnorm(100)
y <- jitter(x)
print(summary(x))
print(head(data.frame(x,y)))
cor(x,y)
plot(x,y)
print(summary(lm(y~x)))
STOP.text.and.image.recording("output.file") # this is the function I am looking for

Update: I was asked way not Sweave, or other options from ReproducibleResearch task view.

The reasons are:

  1. I don't (yet) know LaTeX
  2. Even knowing LaTeX, I want something with simple defaults to simply dump all the outputs together, and in order. "simply" means - as little extra code/file management overhead as possible.

I understand that something like sweave or brew are more scalable, but I am looking to see if there is a more "simple" solution for smaller projects/scripts.

Answer

Jeromy Anglim picture Jeromy Anglim · May 21, 2012

As of 2012 knitr provides a perfect solution to this problem.

For example, create a file with an rmd extension. Wrap your code in a couple of commands as follows:

```{r}
x <- rnorm(100)
y <- jitter(x)
print(summary(x))
print(head(data.frame(x,y)))
cor(x,y)
plot(x,y)
print(summary(lm(y~x)))
```

You can convert it into a self-contained HTML file in several ways. In RStudio you just press a single button Knit HTML. This is the HTML file produced; to actually view how the HTML displays in a browser, save the file and open it.

Images code, and output are interweaved as you might expect.

Of course, you can and typically would divide up your file into multiple R code chunks. But the point is, you don't have to.

Here are another couple of examples I've created: