knitr pandoc: "cannot produce pdf output with pdf writer" - r

Up front: using pandoc() in knitr, it complains when trying to compile .md or .Rmd into a PDF.
I'm streamlining the process for reproducible research, as has been documented in many places. I'm using pandoc and knitr and producing great documents. I'm also trying to streamline for some co-workers who are not as adept with programming, yet we're trying to use similar files. There are several options for "user friendly" markdown-centric editors, and for several reasons I'm leaning on RStudio (for them, emacs/ess for me, but that's different).
My workflow: give them a markdown (.md or .Rmd) file and have them be able to make changes and optionally re-render it into a PDF. Unfortunately, RStudio does not (AFAICT) allow setting templates or other arbitrary pandoc configuration parameters (e.g., chapters, number-sections), so using pandoc() in R/knitr makes a lot of sense here.
Using whitepaper.Rmd as the input file, I run pandoc('whitepaper.Rmd', 'pdf') in R and immediately get:
> pandoc('whitepaper.Rmd', 'pdf')
executing pandoc -t latex --standalone --smart --number-sections --template=report.tex -f markdown -t pdf -o whitepaper.pdf "whitepaper.Rmd"
pandoc.exe: cannot produce pdf output with pdf writer
Error in (function (input, format, ext, cfg) : conversion failed
I explicitly have "t:latex" in my knitr-specific header, though without it, pandoc() is still adding "-t pdf" to the system call, something that pandoc.exe does not accept.
With troubleshooting, the command works just fine if I remove '-t pdf', so it seems that there is nothing wrong with the input file itself:
> system('pandoc -t latex --standalone --smart --number-sections --template=report.tex -f markdown -o whitepaper.pdf "whitepaper.Rmd"')
There have been numerous other conversations regarding this topic: 14586177, 14508429, 15258233, and the heavily-discussed 11025123. They all resolve to solutions that require command-line work, extra middle-steps, external Makefiles, or knit2pdf() (which uses texi2pdf, not desired).
The constraints as I see them:
operate easily within the R environment;
take advantage of Yihui's "<!--pandoc ... -->" in-file configuration (which allows
me to continue to switch arbitrarily between my templates, for one of several examples);
preferably, execute this with a single "standardized" command (i.e., "pandoc('whitepaper.Rmd', 'pdf')").
... so that, once the parameters are set in-file, editing and re-rendering is relatively brain-dead.
I can patch and overwrite Yihui's knitr:::pandoc_one() to remove the offending addition of '-t' and format, but I wonder what side-effects that might have elsewhere. This solution isn't sustainable nor "The Right Way (tm)".
Suggestions for "Right Ways (tm)" to solve this problem? Am I missing an easy/obvious solution?
BTW: thanks, Yihui Xie, for knitr, and John MacFarlane for pandoc. Awesomeness!
(Perhaps I could submit patch suggestions to either or both to work around for my use-case, though if it's just me then it might not be worthwhile.)

I think all there information you need is there in ?pandoc, which includes the example of running system("pandoc -h") to see possible output formats. From that you learn that
Output formats: asciidoc, beamer, context, docbook, docx, dzslides,
epub, epub3,
fb2, html, html5, json, latex, man, markdown, markdown_github,
markdown_mmd, markdown_phpextra, markdown_strict, mediawiki,
native, odt, opendocument, opml, org, pdf*, plain, revealjs,
rst, rtf, s5, slideous, slidy, texinfo, textile
[*for pdf output, use latex or beamer and -o FILENAME.pdf]
So basically format = "pdf" is invalid, you should use pandoc("tmp.Rmd", format = "latex", ext = "pdf") (and acutally the ext="pdf" part is the default, according to ?pandoc, so all you really need is pandoc("tmp.Rmd", "latex")). As for why pandoc('whitepaper.Rmd', 'pdf') resulted in a call with -t pdf, well, you told it to do that in the second argument to your pandoc() call.

Related

What is the best way to write down in-line math equations in a jupyter notebook to have best LaTeX results?

When I am writing math equations in a markdown cell of a jupyter notebook, I casually put all of that in $ ... $. Today, I converted an .ipynb file to .tex, and realized most of these equations are converted into messy stuff in the output pdf. For instance, I realized it is converting all '$'s into '$'s.
This is an example of what has happened:
Jupyter Notebook markdown:
$ \nabla ^{2} f(x) = \frac{-1}{(x+1)^{2}} $
Tex Output:
\$ \nabla \^{}\{2\} f(x) = \frac{-1}{(x+1)^{2}} \$
Does anyone have any ideas why this is happening? Is there a better way to write down in-line math equations so that it is more compatible with LaTeX?
If you are eventually going to LaTeX version, the traditional advice is spelled out in minrk's comment from November 8 of 2012:
"The best solution for that right now would be to use 'raw' cells instead of markdown, and just type LaTeX as you would. Then use nbconvert to turn the ipynb to TeX (code, figures and all), and run latex to render that to PDF, etc. You don't get live-rendered TeX in the browser like you do with MathJax / Markdown, but you do still have TeX / code in one document."
The step where you are converting now is probably using nbconvert under the hood even if you aren't directly. (You may be using it directly since you tagged with 'nbconvert`.)
Alternatively, if you are going to LaTeX ultimately, you may want to use a code cell and use the LaTeX magic cell line at the start of that cell. See here and here about %%latex cell magic. (You'll note it is also mentioned among the StackOverflow thread I referenced earlier.) In regards to the %%latex cell magic, I suggest actually consulting the link that leads use in an example notebook in this post because it seems it has to be full-blown LaTeX code and not just simple equations that work easily elsewhere with just dollar signs bracketing them, i.e., MathJax.
I tried that option with your equation and when I output the notebook as LaTeX, I didn't see additional backslashes added. (I didn't however actually try rendering the LaTeX, and so I cannot address if all the cruft/boilerplate that Jupyter is adding causes any issues for downstream useability.)

xelatex, luatex issues when building pdf of demo book

I can build the gitbook of the demo just fine.
If I attempt to build a pdf, the .tex file is made by pandoc, but xelatex compilation bombs. I get a message in the Build window that's incomplete.
If I manually compile in the shell, I get the following output. Short story-- it would seem that there's code somewhere, probably in pandoc, that uses
\xetex_if_engine:F and
\luatex_if_engine:TF
which apparently have been non-functional since 1-1-2017.
But I can't be the first person to try to compile a pdf since January. Any ideas?
The LaTeX log shows LaTeX2e <2011/06/27>, which is too old, and you will need to refresh your filename database (FNDB) as instructed here,

workflow between Latex and R screwed

Trying to write my second Latex file
\documentclass{article}
\title{simple Sweave script}
\usepackage{/Users/Brenden/Documents/R/R-2.15.1/share/texmf/tex/latex/Sweave}
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
File saved with .Rnw as extension. I could then use Sweave under R to convert the file to tex. I then run pdflatex under cmd to get my .pdf file. R is stored under /Users/Brenden/Documents. MiKTex is stored under /Users/Brenden/Desktop.
It is said that usually the line of "usepackage" is not needed, as when I run Sweave under R, a line of "usepackage{Sweave}" will be added to the tex file which is stored under /Users/Brenden/Documents. However, if I don't put in userpackage line, when I run pdflatex under cmd (either under /Documents or /Desktop), I got a messsage that says "Sweave.sty not found". So I have been through this trouble by always adding a line of usepackage with a detailed path to help circumvent the problem. Although the "Sweave.sty not found" problem is circumvented, I do notice that when I run pdflatex under cmd, I got the response
LaTeX Warning: You have requested package '/Users/Brenden/Documents/R/R-
2.15.1/share/texmf/tex/latex/Sweave', but the package provides "Sweave'.
Then it runs through several files with .sty under MiKTex
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\base\ifthen.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphicx.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\keyval.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphics.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\trig.sty)
...
to eventually create a .pdf
From another post on Stackoverflow, it is said, "That path is set automatically when you install LaTeX; it's your personal texmf tree and you can put any style or class files you want LaTeX to find there. The directory names don't matter, it searches recursively in them for Sweave.sty". To me, however, clearly my MiKTex could not find the Sweave.sty unless I specify the path. And even with the path specification, LaTex still gives me a warning. Could someone explain to me where I screwed up (during installing MiKTex, perhaps? ) so that I could help MiKtex find its way to Sweave without my specifying the path?
Thank you.
In the MiKTeX Settings program, there is a tab called "Roots". It is there that you can specify where additional .sty files can be found. In your case, I believe that you will want to add C:\Users\Brenden\Documents\R\R-2.15.1\share\texmf as an additional root. Doing this, any of the TeX programs will be able to find Sweave.sty whether run from inside R or from the command line.
It is annoying to be always distracted by little devils like this (new concept texmf tree, endless environment variables TEXINPUTS, SWEAVE_STYLEPATH_DEFAULT, ...). You will never worry about LaTeX packages if you use knitr, and if you like the Sweave style, you can simply put render_sweave() in the document like:
\documentclass{article}
\title{simple Sweave script}
<<setup, include=FALSE>>=
render_sweave()
#
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
Save it as, say, test.Rnw and compile it with
library(knitr); knit('test.Rnw') # or knit2pdf('test.Rnw')
And I guess you are probably better off without render_sweave() (i.e. use the default LaTeX style in knitr).
I suspect the path referred to in the other post is the path to your personal texmf tree, which is not where Sweave puts it. One option is to move it to your personal texmf tree, but the usual method nowadays, I believe, is to run pdflatex from within R, like this:
texi2dvi("foo.tex", pdf = TRUE)
I think you can also have Sweave add the full path automatically by adding
export SWEAVE_STYLEPATH_DEFAULT="TRUE"
to your .bashrc file, or whatever the equivalent would be on your system.
At the command line, R CMD sets up the environment with variables appropriate for running R, for instance on Windows
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD set
includes (this is not found if one types set at the command line)
TEXINPUTS=.;c:/PROGRA~1/R/R-215~1/.1/share/texmf/tex/latex;
and so
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD pdflatex myfile.tex
will find Sweave.sty. Also, tools::texi2dvi can be invoked from within R.
I eventually end up with the following solution:
install.packages("tinytex")
require("tinytex")}
install_tinytex(force = TRUE)
Sweave( "Report.Rnw" , encoding = "utf8" )
xelatex('Report.tex')
This code install TinyTex, then you can compile with pdflatex(), xelatex() or lualatex().

More efficient R / Sweave / TeXShop work-flow?

I've now got everything to work properly on my Mac OS X 10.6 machine so that I can create decent looking LaTeX documents with Sweave that include snippets of R code, output, and LaTeX formatting together. Unfortunately, I feel like my work-flow is a bit clunky and inefficient:
Using TextWrangler, I write LaTeX code and R code (surrounded by <<>>= above and # below R code chunk) together in one .Rnw file.
After saving changes, I call the .Rnw file from R using the Sweave command
Sweave(file="/Users/mymachine/Documents/Assign4.Rnw",
syntax="SweaveSyntaxNoweb")
In response, R outputs the following message:
You can now run LaTeX on 'Assign4.tex'
So then I find the .tex file (Assign4.tex) in the R directory and copy it over to the folder in my documents ~/Documents/ where the .Rnw file is sitting (to keep everything in one place).
Then I open the .tex file (e.g. Assign4.tex) in TeXShop and compile it there into pdf format. It is only at this point that I get to see any changes I have made to the document and see if it 'looks nice'.
Is there a way that I can compile everything with one button click? Specifically it would be nice to either call Sweave / R directly from TextWrangler or TeXShop. I suspect it might be possible to code a script in Terminal to do it, but I have no experience with Terminal.
Please let me know if there's any other things I can do to streamline or improve my work flow.
I use a Makefile of the following form for my Sweave documents:
pdf: myfile.tex
R CMD texi2pdf myfile.tex
myfile.tex: myfile.Rnw
R CMD Sweave myfile.Rnw
Then I can build the document in one step in the Mac OS Terminal by running the command make pdf
I'm sure there is a way to bring this closer to your one-click goal in Mac OS X, but this works well enough for me.
One-click Sweaving is easy to do in TeXShop using the Sweave.sh script by Gregor Gorjanc.
Get it from http://cran.r-project.org/contrib/extra/scripts/Sweave.sh and put it in your ~/Library/TeXShop/bin/ folder.
Then add the following files to your ~/Library/TeXShop/engines/ folder:
As Sweave.engine:
#!/bin/bash
~/Library/TeXShop/bin/Sweave.sh -ld "$1"
As SweaveNoClean.engine:
#!/bin/bash
~/Library/TeXShop/bin/Sweave.sh -nc -ld "$1"
You'll have to set the permissions on Sweave.sh and the two engine files to allow execution.
To Sweave with one click, restart TeXShop after adding these files, open the Sweave document (with Rnw extension) and in the dropdown menu above the document window, change it from LaTeX to Sweave or SweaveNoClean.
BEWARE: The "Sweave" option wll clean up after itself, deleting all the extra files LaTeX and Sweave creates. If your file is called myfile.Rnw, this will include files called myfile.R and myfile.tex. So a word to the wise: make sure the basename of your Rnw file is unique; then nothing unexpected will be written over and then deleted.
The SweaveNoClean option does not clean up after itself. This makes sure you don't delete anything unexpected; though it could still write over a file called myfile.tex if you Sweave a myfile.Rnw. This also doesn't delete any graphics that have been created, in case you want to have them separate from your full typeset document.
On the bash shell command line:
R CMD Sweave foo.Rnw && pdflatex foo.tex
Runs Sweave, and if that succeeds it goes on to do pdflatex. Out pops a pdf. If you've got this in a bash Terminal then just hit up-arrow to get it back and do it again. And again. And Again.
Makefile solution also good.
RStudio has a button that does this in one go. One caveat is that it runs in its own session, so any workspace variables you may have set are ignored.
Just a note: you can actually call things like pdflatex etc. directly from R using texi2dvi (in the tools package). For example:
Sweave(file="/Users/mymachine/Documents/Assign4.Rnw")
texi2pdf("Assign4.tex")
would compile your Rnw file into a pdf. Thus, no need to leave R to handle the tex->pdf step.
I use these (saved as sweave.engine and sweavebibtex.engine) for custom engines in texshop. I usually work up a code chunk in R, then copy the block into the rnw file I have open in texshop. I'd love a solution that lets me do syntax highlighting and spelling correction of R and tex in the same document (that isnt emacs).
#!/bin/bash
echo 'SWEAVE | PDFLATEX. Custom engine--Akasurak-16Nov2009'
export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
pdflatex "${1%.*}"
and the second, for doing bibtex as well:
#!/bin/bash
date
before="$(date +%s)"
echo 'SWEAVE | PDFLATEX | BIBTEX | PDFLATEX | PDFLATEX. Custom engine--Akasurak-16Nov2009'
#Updated 20Jul2010 for auto including Sweave.sty
export PATH=$PATH:/usr/texbin:/usr/local/bin
R CMD Sweave "$1"
R CMD pdflatex "${1%.*}"
bibtex "${1%.*}.aux"
R CMD pdflatex "${1%.*}"
R CMD pdflatex "${1%.*}"
after="$(date +%s)"
elapsed_seconds="$(expr $after - $before)"
date
echo Elapsed time '(m:s)': $(date -r $elapsed_seconds +%M:%S)
Can't say they are the best way of doing things, but they do work.
I use either Aquamacs or Eclipse to do the editing of the .Rnw file, then I use the following shell function to compile & view it:
sweaveCache () {
Rscript -e "library(cacheSweave); setCacheDir(getwd());
Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Notice that I'm using the cacheSweave driver, which helps avoid constantly re-executing code sections that take a long time to run.
BTW, I'm also trying to switch over to Babel instead of Sweave; not sure which I'll end up using more often, but there are definitely aspects of Babel that I like.
The best solution is here: you create a new *.engine for TeXShop to use, then typeset using the shortcut or the 1 button.
http://cameron.bracken.bz/sweave-for-texshop
Cameron is also very responsive, so I highly recommend his solution.
If you are open to switching to a (paid) solution, TextMate has a Sweave plugin that takes you from .Rnw to PDF in one step: Sweave, typeset, and view. Combined with Skim, which can be configured to reload PDFs, it makes tweaking files pretty easy.
I had this same issue (I use Mac OSX) and I opted to download Eclipse Classic 3.6.2. and then installed the StatET plugin. It's a bit hairy to get set up but once you do this environment is nice because you can one-click compile your .Rwn Sweave document using pdflatex and set options for your favorite viewer so the .pdf automatically pops up when you compile like it does in TeXShop. You can do this in TeXShop as well, but TeXShop is lousy for debugging .Rnw files and it doesn't highlight the R-code in the .Rwn file. In Eclipse you can customize the syntax highlighting (not the greatest from the Texclipse end, but ok) so that you can easily distinguish between your R and LaTeX code. You can also launch the R console from within Eclipse and it has a graphical object browser. Anyway, I could go on. If you want details about how to get it all installed, message me.
Guess I'm late to the party on this, but I put together a webpage that documents my Sweave workflow based on Eclipse (with one-touch sweave):
http://www.stanford.edu/~messing/ComputationalSocialScienceWorkflow.html

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

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:
I don't (yet) know LaTeX
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.
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:
Getting started with R Markdown
Case study in using R Markdown
If you know LaTeX, sweave will likely be your best bet. odfWeave is a similar mechanism but for embedding the code in an OpenOffice.org file. For HTML there is the R2html package. But all will likely require you to break the code up a little bit to get the best out of the systems. Alternatively, your sweave/odfweave/html template could source the data generation aspects of the script in a single code chunk, with the output display (print() statements) placed where required. Your graphics could also be called within the script to produce the figures to embed in the document as separate files, which you then include by hand in the template.
For example (and this isn't a full .Rnw file for running through sweave) in a sweave file you'd put something like this high up in the template which sources the main part of the R script that will do the analysis and generate the R objects:
<<run_script, eval=TRUE, echo=FALSE, results=hide>>=
source("my_script.R")
#
Then you will need to insert code chunks where you want printed output:
<<disp_output, eval=TRUE, echo=FALSE, results=verbatim>>=
## The results=verbatim is redundant as it is the default, as is eval=TRUE
print(summary(x)) ## etc
#
Then you will need chunks to insert the figures.
Separating your analysis code from the output (printed and/or figures) is probably good practice as well, especially if the analysis code is expensive in compute terms. You can run it once - or even cache it - whilst updating the output/display code as you need to.
Example Sweave File
Using csgillespie's example sweave file I would set things up like this. First the my_script.R file containing the core analysis code:
x <- rnorm(100)
y <- jitter(x)
corXY <- cor(x,y)
mod.lm <- lm(y~x)
Then the Sweave file
\documentclass[12pt]{article}
\usepackage{Sweave}
\begin{document}
An introduction
<<run_analysis, eval=TRUE,echo=FALSE, results=hide>>=
source("my_script.R")
#
% Later
Here are the results of the analysis
<<show_printed_output, echo=FALSE>>=
summary(x))
head(data.frame(x,y))
#
The correlation between \texttt{x} and \texttt{y} is:
<<print_cor, echo=FALSE>>=
corXY
#
Now a plot
\begin{figure}[h]
\centering
<<echo=FALSE, eval=TRUE, fig=TRUE, width=6, height=4>>=
plot(x,y)
#
\caption{\textit{A nice plot.}}
\end{figure}
\end{document}
What you seem to be wanting doesn't exist; a simple way of combining R code and output into a document file. That is if you don't consider sweave and its ilk simple. You might need to rethink what you want to do or how you arrange your analysis and graphics and output code, but you are likely best served looking at one of the suggested options (sweave, odfweave, brew, R2html).
HTH
I would encourage you to use Sweave, but a rudimentary functionality that is not pretty can be achieved with sink().
A regular txt file:
sink(file = "test.txt", type = "output")
summary(cars)
sink()
or add some HTML tags:
sink(file = "tal_test.html", type = "output")
cat("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"", "\n")
cat("\"http://www.w3.org/TR/html4/strict.dtd\">", "\n")
cat("<HTML>", "\n")
cat("<HEAD>", "\n")
cat("<TITLE>My first HTML document</TITLE>", "\n")
cat("</HEAD>", "\n")
cat("<BODY>", "\n")
summary(cars)
cat("</BODY>", "\n")
cat("</HTML>", "\n")
sink()
I wrote a script called Roux about a year ago which does this. I wanted to be able to create HTML transcripts from running an R script, including any images, without having to change the script.
You call Roux from the command line, like this:
roux example.R
and roux will:
run the script in R (requiring the Roux package first automatically)
syntax highlight the .Rout output using Pygments
insert images in the correct location
the Roux R package is a very small R package which modifies plot() and some other functions to automatically write to a random filename rather than the default interactive graphics device.
I have used this a lot, and it works really well for me, although I'm sure if more people use it with new packages then minor issues will arise, most likely that you'll have a different function which generates a graph and Roux won't know that it should open a PNG device for you.
Since speaking with Tal about this I have updated and improved the code, and it's now up here:
http://bitbucket.org/ananelson/roux/src
so if you run into any issues, please report them to the issue tracker there on Bitbucket.
I have added support for LaTeX transcripts so you can easily create PDFs which have the transcript of your R script including images. (You can see an example if you look in the example-output directory, find the "raw" link to download it.)
You do need to have Python and the Pygments python library intalled. If you have an older version of Python and run into any issues, please let me know.
I wrote about Roux on my blog but didn't publicize it that much because my efforts have been focused on a new project called Dexy which is intended as a replacement for Sweave. If you want more flexibility and control or are interested in literate documentation then you might want to check out Dexy too.
You mentioned sweave in your question but not really why it isn't suitable. Your question seems perfect for Sweave. In fact, your example code could have came from the second Sweave example.
Example Sweave file
If you know Latex then Sweave isn't that difficult. Here's your example file as a Sweave file:
\documentclass[12pt,BCOR3mm,DIV16]{scrreprt}
\usepackage{Sweave}
\begin{document}
An introduction
<<eval=TRUE,echo=TRUE>>=
x <- rnorm(100)
y <- jitter(x)
print(summary(x))
print(head(data.frame(x,y)))
cor(x,y)
#
Now a plot
\setkeys{Gin}{width=0.5\textwidth}
\begin{figure}[h]
\centering
<<echo=FALSE, eval=TRUE, fig=TRUE, width=6, height=4>>=
plot(x,y)
#
\caption{\textit{A nice plot.}}
\end{figure}
\end{document}
Under linux, just save the file as tmp.Rnw. Then
R CMD Sweave tmp.Rnw
pdflatex tmp.tex
There is also LyX, which has an Sweave interface. The R / LyX / Sweave interface code is on CRAN at http://cran.fhcrc.org/contrib/extra/lyx/. LyX itself is in most of the Linux distros. All of this magic can be made to work on Windows, but it's definitely non-trivial. On Windows, I'd recommend Inference for R from Blue Reference for literate R progamming.
Well, I just remind that I was using Asciidoc for short reporting or editing webpage. Now there's an R plugin (ascii on CRAN), which allows to embed R code into an asciidoc document. The syntax is quite similar to Markdown or Textile, so you'll learn it very fast.
Output are (X)HTML, Docbook, LaTeX, and of course PDF through one of the last two backends.
Unfortunately, I don't think you can wrap all your code into a single statement. However, it supports a large number of R objects, see below.
> methods(ascii)
[1] ascii.anova* ascii.aov* ascii.aovlist* ascii.cast_df*
[5] ascii.character* ascii.coxph* ascii.CrossTable* ascii.data.frame*
[9] ascii.default* ascii.density* ascii.describe* ascii.describe.single*
[13] ascii.factor* ascii.freqtable* ascii.ftable* ascii.glm*
[17] ascii.htest* ascii.integer* ascii.list* ascii.lm*
[21] ascii.matrix* ascii.meanscomp* ascii.numeric* ascii.packageDescription*
[25] ascii.prcomp* ascii.sessionInfo* ascii.simple.list* ascii.smooth.spline*
[29] ascii.summary.aov* ascii.summary.aovlist* ascii.summary.glm* ascii.summary.lm*
[33] ascii.summary.prcomp* ascii.summary.survfit* ascii.summary.table* ascii.survdiff*
[37] ascii.survfit* ascii.table* ascii.ts* ascii.zoo*
Non-visible functions are asterisked
This is in light of romunov's answer, but still. You can just write your own print that wraps the output in some HTML formatting and embeds the output to a HTML file. The same can be done with pictures with Data URI scheme, for instance by using img function from base64 R package.
You can use the R2HTML package to output a session to html and there are some similar functions in the TeachingDemos package (see txtStart) for output to enhanced text and word (via R2wd). Non-graphics commands will be included in the file automatically and the current plot can be inserted by a single command.
Through the wonders of twitter, someone reached out and sent me a link to this page, regarding a package called "roux". It was created a year ago, and I have never heard about it (apparently neither have most of you).
This package seems to do exactly what I was looking for in my question, although the installation seems non trivial.
I hope to play with this solution and also to see if other R members might go into this project to better enhance R.
good suggestion by #znmeb to try Lyx - a more word-like front end for LaTeX, and as the documentation points out, there is a good article of its use with Sweave on page 2 of this edition of R news
This is how I did it in Ubuntu 10.04 follwoing the guidelines in the lyx sweave repository:
sudo apt-get install lyx
cd ~./lyx
wget http://cran.fhcrc.org/contrib/extra/lyx/preferences
cd layouts
wget http://cran.fhcrc.org/contrib/extra/lyx/literate*
wget http://cran.fhcrc.org/contrib/extra/lyx/literate-article.layout
wget http://cran.fhcrc.org/contrib/extra/lyx/literate-book.layout
wget http://cran.fhcrc.org/contrib/extra/lyx/literate-report.layout
wget http://cran.fhcrc.org/contrib/extra/lyx/literate-scrap.inc
cd ~/texmf/tex
wget http://www.biostat.jhsph.edu/~rpeng/ENAR2009/Sweave.sty
start Lyx
Preferences -> Reconfigure
restart Lyx
File -> new
Document -> Settings -> Document Class -> article (Sweave noweb)
useful links:
lyx sweave repository
R news article about Lyx and Sweave

Resources