# R Programming/Publication quality output

R Programming
* R Basics
** Introduction
** Sample Session
** Manage your workspace
** Settings and Installation
** Documentation
** Control Structures
** Working with functions
** Debugging
** Using C or Fortran
** Utilities
** Estimation utilities
** Packages
* Data Management
** Data types
** Working with data frames
** Importing and exporting data
** Text Processing
** Times and Dates
* Graphics
** Grammar of graphics
* Publication quality output
* Descriptive Statistics
* Mathematics
** Optimization
** Probability Distributions
** Random Number Generation
* Statistical Core Methods
** Maximum Likelihood
** Method of Moments
** Bayesian Methods
** Bootstrap
** Multiple Imputation
** Nonparametric Methods
* Regression Models
** Linear Models
** Quantile Regression
** Binomial Models
** Multinomial Models
** Tobit And Selection Models
** Count Data Models
** Duration Analysis
* Time Series
* Factor Analysis
* Classification
** Ordination
** Clustering
* Network Analysis
* High Performance Computing
** Profiling R code
** Parallel computing with R
* Appendix
** Sources
** Index

## Formatting numbers

You can use the format function to control the number of digits and other characteristics of a displayed object.

## Sweave

Sweave is a literate programming language which integrates LaTeX and R code. The Sweave file generates a LaTeX file and an R file which can in turn be compiled. Roger Koenker, Meredith and Racine (2009) and Charles Geyer argue that Sweave favors reproducible econometric/statistical research.
There are some alternatives to Sweave for literate programming. One of them is Babel which is included in Emacs Orgmode. This tool allow export to LaTeX and HTML. It is also possible to include code chunks for various programming languages (R, Ruby, etc).

### Syntax

The main idea is that you write a file which includes LaTeX and R code. LaTeX code begins with @ and R code with <<>>= (some options can be included between << and >>).
The file is stored with extension .Rnw or .rnw. At the end, you extract from this file an R file using Stangle and a LaTeX file using Sweave. Here is an example with a file called file.Rnw which generates file.tex and file.R
Then you can run LaTeX on your file.tex. This can be done using the system function or texi2dvi.
Note that you may need to download Sweave.sty from the internet since it is not part of the standard MikTeX distribution.
You can also add your results in your text using the \Sexpr function.

### Options

There are some options. These options can be included for each code chunk or in the Sweave command.
* For figures, you can either include them in the tex file using fig=T or not include them using fig=F.
By default, figures are exported as pdf and eps files. If you only want one format suppress the other one with pdf=F or eps=F option.
* The R code can be displayed in the tex file using echo=T. If you don't want to include it in the tex file, use echo=F.
* The R code can be evaluated using eval=T. If you don't want to evaluate the R code, use eval=F.
* The results :
** results=tex treats the output as LaTeX code
** results=verbatim treats the output as Verbatim (the default)
** results=hide does not include the results in the LaTeX output
These options can be passed to the Sweave function.
They can also be passed to each code chunk.

### Text editor for Sweave

The main issue with Sweave is that few text editors include syntax highlighting for Sweave. Here are some exceptions :
* RStudio is a very good solution. It is easy to install and use and it includes buttons to run Sweave files.
* Vim provides syntax highlighting for Sweave file (R no web syntax)
* Emacs + ESS (Emacs Speaks Statistics) provides full support for Sweave file. It includes a keyboard shortcut to run Sweave files and syntax highlighting switching between LaTeX and R.
* Eclipse StatET plugin provides support for Sweave (LaTeX/R) documents with all basic features (syntax highlighting, bracket matching, toggle comment, ...) and with detection of R chunks.

### See also

Some example of Sweave documents :
* Charles Geyer foo.Rnw example
* Julien Barnier's introduction to R (document in french)
* trick : type filetype:Rnw or filetype:Snw in Google to get Sweave files
* Notice that you can find lots of examples by browsing in the R library folder. The documentation is often written using Sweave and the Sweave file is often included in the package. See for instance in the np package the doc folder.
Some handouts :
* "Literate Programming with Sweave and DOCSTRIP" (pdf) by Michael Lundholm
* Charles Geyer 2008 "An Sweave Demo" (pdf) (short)
* Learning To Sweave in APA Style
Some packages
* pgfSweave package
* ascii package
* cacheSweave
* exam automatic generation of exams
Some alternative literate programming packages :
* odfWeave package to Sweave with OpenOffice.
* knitr package
* decumar, a literate programming interface for R by Hadley Wickham
* relax package
* wikirobot is similar to Sweave but works with MediaWiki.

## Pubprint

Pubprint is a small utility that is able to transform the output of statistical tests to publication ready output. Pubprint is able to export outputs to severall formats (HTML, LaTeX, Markdown and plain text), but unfortunately supports only the APA style (publication style of the American Psychological Association). However, this style is widely used and may be appropriate in more cases.

### Example

Obviously pubprint prints a LaTeX formatted string, but changing the output format is possible (according to the manual pubprint is intended to use with knitr and detects output format automatically if it is used with it):
The output can be pasted into a documented or may included in a knitr/sweave \Sexpr statement.

## Export to LaTeX

R has lots of functions which allow it to export results to LaTeX.

### General functions

toLatex in the utils package.
* Note that toLatex does not handle matrices.
* toLatex has been adapted to handle matrices and ftables in the memisc package.
* mat2tex (sfsmisc) exports matrix to LaTeX.
* tex.table (cwhmisc) package exports a dataframe into a LaTeX table.
* xtable (xtable) exports various objects, including tables, data frames, lm, aov, and anova, to LaTeX.
See also :
* The highlight package by Romain François exports R code to LaTeX and HTML.
* format.df and latex in the Hmisc package.
* The MEMISC and the quantreg packages include other latex function.

### Descriptive statistics

* estout package.
* The reporttools package include some functions for table of descriptive statistics.

### Estimation results

* The stargazer package provides an easy way to export the results of regressions to LaTeX
* texreg provides the same kind of features.
* The estout package provides functions similar to the Stata's esttab and estout utilities. Estimates are stored using eststo and printed using esttab. They can be exported to CSV and LaTeX. These functions support lm, glm and plm objects (see plm package).
* apsrtable (apsrtable) exports the results of multiple regression to LaTeX in a way similar to the American Political Science Review publication standard.
* The xtable (xtable package) exports dataframes, matrix, estimation results. xtable can also be used to export the results to an HTML file.
* The outreg function developped by Paul Johnson is similar to the Stata outreg function. See "R you ready ?" post on this topic.
* mtable and toLatex in the 'memisc package.

## Export to HTML

The rpublisher is a literate programming language which publish results in HTML (it is based on python and was last updated in 2008).
See R2HTML, xtable, hwriter, prettyR, highlight, HTMLUtils
wiki.table in the hacks package export a matrix or a dataframe into Mediawiki table markup (as used on this wiki and many others).

## References

* ↑ The Sweave Homepage http://www.stat.uni-muenchen.de/~leisch/Sweave/
* ↑ http://www.econ.uiuc.edu/~roger/repro.html
* ↑ Meredith, E. and J.S. Racine (2009), “Towards Reproducible Econometric Research: The Sweave Framework,” Journal of Applied Econometrics, Volume 24, pp 366-374.
* ↑ Charles Geyer "Why Reproducible Research is the Right Thing" http://www.stat.umn.edu/~charlie/Sweave/
* ↑ Babel in Emacs Orgmode http://orgmode.org/worg/org-contrib/babel/intro.html
* ↑ Ista ZahnLearning To Sweave in APA Style, The PracTeX Journal 2008, 1
* ↑ decumar git archive : http://github.com/hadley/decumar
* ↑ wikirobot http://r-forge.r-project.org/projects/wikirobot/
* ↑ See the LaTeX Wikibook if you want to learn about LaTeX
* ↑ reporttools: R Functions to Generate LaTeX Tables of Descriptive Statistics
* ↑ http://www.r-statistics.com/2013/01/stargazer-package-for-beautiful-latex-tables-from-r-statistical-models-output/
* ↑ http://www.r-bloggers.com/texreg-a-package-for-beautiful-and-easily-customizable-latex-regression-tables-from-r/
* ↑ estout : http://repec.org/bocode/e/estout/
* ↑ xtable on dataninja blog
* ↑ The outreg function http://pj.freefaculty.org/R/WorkingExamples/outreg-worked.R
* ↑ Stata outreg http://ideas.repec.org/c/boc/bocode/s375201.html
* ↑ rpublisher : http://code.google.com/p/rpublisher/