Sweave syntax highlighting in output - r

Has anyone managed to get color syntax-highlighting working in the output of Sweave documents? I've been able to customize the output style by adding boxes, etc. in the Sweave.sty file as follows:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontseries=bc,frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontseries=bc}
And I can get the minted package to do syntax highlighting of verbatim-code blocks in my document like so:
\begin{minted}{perl}
use Foo::Bar;
...
\end{minted}
but I'm not sure how to combine the two for R input sections. I tried the following:
\DefineVerbatimEnvironment{Sinput}{minted}{r}
\DefineVerbatimEnvironment{Scode}{minted}{r}
Any suggestions?

Yes, look at some of the vignettes for Rcpp as for example (to pick just one) the Rcpp-FAQ pdf.
We use the highlight by Romain which itself can farm out to the hightlight binary by Andre Simon. It makes everything a little more involved---Makefiles for the vignettes etc pp---but we get colourful output from R and C/C++ code. Which makes it worth it.

I have a solution that has worked for me, I have not tried it on any other systems though so things may not work out of the box for you. I've posted some code at https://gist.github.com/797478 that is a set of modified Rweave driver functions that make use of minted blocks instead of verbatim blocks.
To use this driver just specify it when calling the Sweave function with the driver=RweaveLatexMinted() option.

Here's how I've ended up solving it, starting from #daroczig's suggestion.
\usepackage{minted}
\renewenvironment{Sinput}{\minted[frame=single]{r}}{\endminted}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{frame=leftline}
\DefineVerbatimEnvironment{Scode}{Verbatim}{}
While I was at it, I needed to get caching working because I'm using large data sets and one chunk was taking around 3 minutes to complete. So I wrote this zsh shell function to process an .Rnw file with caching:
function sweaveCache() {
Rscript -e "library(cacheSweave); setCacheDir(getwd()); Sweave('$1.Rnw', driver = cacheSweaveDriver)" &&
pdflatex --shell-escape $1.tex &&
open $1.pdf
}
Now I just do sweaveCache myFile and I get the result opened in Preview (on OS X).

This topic on tex.StackExchange might be interesting for you, as it suggest loading the SweaveListingUtils package in R for easy solution.

Related

Indenting VSCode like RStudio

I'm using VS Code and i miss RStudio's ctrl+i to indent lines.
I've read stuff online about LSP and other extensions and formatting with shift+alt+F but all i get is linter.
So, whats the equivalent if is there at all?
Found a solution but there a few things to take note.
First, VSCode notive options are language-agnostic, meaning it can't indent R code 'cause it doesn't understand it. You got to download extensions to make i work.
Extensions required are
Yuki Ueda's R for language support
REditorSupport's R LSP Client
Also, in order to R LSP Client to work, CRAN package {languageserver} is required.
Then, usage. If you're working functions, differently from RStudio in which one can hit ctrl+i and that'd indent that specifically line or selection, this solution works only if one selects the entire function. If you have functions inside another, you gotta indent everything (won't work for just a foo inside another).

Need the filename of the Rnw when knitr runs in rStudio

When working on a reproducible research project, I would like to know the name of the Rnw file that is being run to use as an R variable.
This would be analogous to inserting an MSExcel filename in a footer
I am using RStudio Server on Ubuntu.
Thank you.
knitr now has a method for this: current_input()
https://github.com/yihui/knitr/issues/701
You can use the following two idioms to fetch the directory and name of the current file in knitr:
knitr:::.knitEnv$input.dir
knitr:::knit_concord$get("infile")
This is independent of RStudio, the knitr package is entirely responsible for this. These are private functions and variables that can change at any time without notice, so if you need something reliable, you might want to file an issue on GitHub.

ESS & Knitr/Sweave: How to source the Rnw file into an interactive session?

This is a terribly simple request, and I can't believe I haven't found the solution to this yet, but I've been searching for it far and wide without luck.
I have an .Rnw file loaded up in Emacs, I use M-n s to compile it.
Everything works well, and it even opens an R buffer. Great. But that buffer
is entirely useless: it doesn't contain the objects that I just sourced!
Example minimal .Rnw file:
\documentclass{article}
\begin{document}
<<>>=
foo <- "bar"
#
\end{document}
Using M-n s, I now have a new R-buffer with a session loaded up, but:
> foo
Error: object 'foo' not found
That is disappointing. I would like to play around with the data interactively.
How do I achieve that? I don't want to be sourcing the file line-by-line, or
region-by-region with C-c C-c or something similar every time I change my code.
Ideally, it should be just like RStudio's source function, that leaves me with
a fully prepared R session.
I haven't tried this with sweave yet, only with knitr.
EDIT: the eval=TRUE chunk option does not seem to result in the correct behaviour.
This behaviour was recently changed in ESS. Now sweave and knitr are executed directly in the global environment, as if when you write it yourself at command line. So wait for a couple of more weeks till ESSv13.09 is out or use the development version.
Alternatively, you can also set ess-swv-processing-command to "%s(%s)" and you will get the same result, except automatic library loading.
For the record, knitr (in contrast to sweave) evaluates everything in it's own environment unless you instruct it otherwise.
[edit: Something went wrong. I don't see the correct .ess_weave any more. Probably some git commit messup again. So it is not fixed in 13.09. Fixing it now. Sorry.]
Open an interactive R session, and then call Sweave directly, I believe like this (untested though). knitr works in the same way, though you need to load the knitr library first.
> Sweave("yourfile.Rnw")
There is some potential for peril here, though. If you call Sweave in a session after doing other things, your code can use things previously in the workspace, thus making your results unreproducible.

Hide and show comments

I'm writing all my scripts on .R file using R for mac. It is convenient to me because there are colors to highlight the type of commands.
I have a many comments following the # symbol that are useful when I forget about the meaning of my script but they tend to blur my script so that it gets harder to find a given command line.
Is there a way to hide and show these comments ? (Using the programm I'm currently using or another one). What would you suggest as the best program to write R script ?
Thanks a lot !
RStudio supports code folding. You can standardize your comment blocks so that they are recognized as code blocks.
For example, enter this into your RStudio editor
#=======================================================
# this is a comment block
# more comments here
# comments upon comments
and then press Alt+L to fold, and Alt+Shift+L to unfold.
Try RStudio for mac. One of the greatest code writing environment for R there is.
You can also try Emacs, which is more like old-fashioned command line editor. You can find a good guide here.

How do I generate reports in R without texi2dvi or TeX installed?

I've been struggling for a week now trying to figure out how to generate reports in R using either Sweave or Brew. I should say right at the beginning that I have never used Tex before but I understand the logic of it.
I have read this document several times. However, I cannot even get a simple example to parse. Brew successfully converts a simple markup file (just a title and some text) to a .tex file (no error). But it never ever converts tex to a pdf.
> library(tools)
> library(brew)
> brew("population.brew", "population.tex")
> texi2dvi("population.tex", pdf = TRUE)
The last step always fails with:
Error in texi2dvi("population.tex", pdf = TRUE) :
Running 'texi2dvi' on 'population.tex' failed.
What am I doing wrong?
The report I am trying to build is fairly simple. I have 157 different analysis to summarize. Each one has 4 plots, 1 table and a summary. I just want
output plot 1,2,3,4
output table
\pagebreak
...
that's it. Can anyone help me get further? I use osx, don't have Tex installed.
thanks
You cannot run this without texi2dvi or TeX installed.
An alternative may be html output -- the hwriter package is useful for that.
That said, if you want to produce pdf out, Sweave is the way to go. Frank Harrell's site has a lot of useful info but all this requires a bit of familiarity with LaTeX so you may need to install and learn that first.
If you are on OSX, might as well install the full tex live
http://mirror.ctan.org/systems/mac/mactex/MacTeX.mpkg.zip
It is a big download, but it will be nice to never have to install additional packages.
Another solution: the ascii package in conjonction to your favorite markup language (asciidoc, txt2tags, restructuredtext, org or textile).
http://eusebe.github.com/ascii/
It may be worthwhile spending a week or so just using LaTeX without R and going through a bunch of introductory LaTeX tutorials.
Thus, when you start producing Sweave or Brew documents and you get errors, you will be better able to identify whether the error is arising from LaTeX or Sweave / Brew.
A couple of Windows tools that make it easy to get started with LaTeX include MikTeX + TeXnicCenter or MikTeX + WinEdt.
Another solution is to try a solution of connecting R to microsoft.
It is much weaker then Sweave, but for basic reporting might be what you need.
You might want to go through the example sessions given here: Exporting R output to MS-Word with R2wd (an example session)
I've also been hearing a lot of good things about the knitr package. It seems to resemble Sweave a lot, but add some more to it. I would definitely take a look at it.

Resources