% Building Packages for R
% Jared P. Lander
% September 4, 2012

```{r setup, include=FALSE}
# set global chunk options
opts_chunk$set(cache=TRUE,fig.path='figures/',dev='png',message=FALSE,fig.align='center',concordance=TRUE,comment='##')
#opts_chunk$set(upload.fun = knitr:::base64_encode)
options(left.brace.newline = TRUE)
```

```{r defn,include=FALSE}
require(hwriter)
require(stringr)
require(RCurl)
defn <- function(terms, defn, font.size=100)
{
    theTable <- data.frame(Term=terms, Definition=defn)
    cat(hwrite(theTable, col.names=F, col.class=c("term", "defn"), border=0, style=sprintf("font-size:%s%s", font.size, "%")))
}

make.image <- function(file, width="100%", align="center")
{
    cat(sprintf("<%s><img src=\"%s\" width=\"%s\" /></%s>", align, knitr::image_uri(f=file), width, align))
}
#make.image(file="modules/PackageBuilding/figures/PackageGrowth.png")
```

## So Many Packages!
<!--- comment -->
```{r many-packages,echo=FALSE,results='asis'}
make.image(file="figures/PackageGrowth.png", width="50%")
```

## CRAN's Home
```{r cran-home,echo=FALSE,results='asis'}
make.image(file="figures/CRAN_Screen.png", width="90%")
```

## The Right Tools
- RStudio
- devtools
- roxygen
- Git
- MingW

<style>
    .term {text-align:right;
            font-weight:bold;
            color:blue;}
    .defn {text-align:left;}
</style>

# Package Basics

## Folders
```{r Folders,echo=FALSE,results='asis'}
cat(defn(terms=c("R", "man", "src", "data", "inst"), defn=c("R Code", "Help Files", "Compiled code such as C/C++/FORTRAN", "Included Data", "Files to be included in binary")))
```

## Files
<table>
    <tr>
        <td class="term">
            DESCRIPTION<br />
            NAMESPACE<br />
            NEWS<br />
            LISCENSE<br />
            README<br />
        </td>
        <td> </td>
        <td class="defn">
            Package information including dependencies<br />
            List of functions exposed to end user<br />
            What has been updated in each version<br />
            Copyright information<br />
            Basic description of package<br />
        </td>
    </tr>
</table>


## DESCRIPTION
```{r description-table,echo=FALSE,results='asis'}
cat(defn(terms=c("Package",
"Type",
"Title",
"Version",
"Date",
"Author",
"Maintainer",
"Description",
"License",
"LazyLoad",
"Depends",
"Imports",
"Suggests",
"Collate",
"ByteCompile"), 
defn=c("Name of package",
"Just use `Package`",
"Verbose Title",
"Current version: v.s.ss",
"Latest build date",
"Name of author",
"Author email address: <name@domain.com>",
"Short description of package",
"License type",
"Just use `yes`",
"Comma separated list of packages to be loaded",
"Comma separated list of packages to use but not load",
"Comma separated list of packages that are nice to have",
"List (no commas) of r files in the R directory in processing order",
"If the package should be Byte Compiled on installation"), font.size=75))
```

## Example DESCRIPTION
<div style="font-size:80%">
Package: coefplot  
Type: Package  
Title: Plots Coefficients from Fitted Models  
Version: 1.1.7  
Date: 2011-10-02  
Author: Jared P. Lander  
Maintainer: <packages@jaredlander.com>  
Description: Plots the coefficients from a model object  
License: BSD  
LazyLoad: yes  
Depends: ggplot2  
Imports: plyr, stringr, reshape2, useful  
Collate: 'coefplot.r', 'modelInfo.r', 'utilities.r', 'coefplot-package.r', 'multiplot.r'  
ByteCompile: TRUE
</div>

## NAMESPACE
```{r namespace-table,echo=FALSE,results='asis'}
cat(defn(terms=c("import", "export", "S3method"), defn=c("Package to use", "Function for end user", "Identify generic methods")))
```

## NAMESPACE Example
<div style="font-size:85%">
S3method(coefplot,lm)  
S3method(coefplot,rxLinMod)  
S3method(coefplot,rxLogit)  
S3method(getModelInfo,lm)  
S3method(getModelInfo,rxLinMod)  
S3method(getModelInfo,rxLogit)  
export(coefplot)  
export(coefplot.lm)  
export(coefplot.rxLinMod)  
export(coefplot.rxLogit)  
export(multiplot)  
export(plotcoef)  
import(ggplot2)  
import(plyr)  
import(reshape2)  
import(stringr)  
import(useful)
</div>

## NEWS Example
__Version 1.1.7__  
Thanks to Felipe Carrillo I have fixed a bug in multiplot.  Previously, if multiple models with the same formula but different data.frames were inputed then they would all have the same name (even if specified with the "names" argument) and only one model would be plotted.  This now works as expected, plotting all the models regardless of identical formulas.

__Version 1.1.6__  
Made change to reshape2::melt so that variable.name and value.name behave properly with new ggplot2

__Version 1.1.5__  
Fixed glitch that didn't plot inner CI for single plots or multipane multiplots

## README Example
Coefplot is a package for plotting the coefficients and standard errors from a variety of models.  Currently lm, glm, rxLinMod and rxLogit are supported.

The package is designed for S3 dispatch from the functions coefplot and getModelInfo to make for easy additions of new models.

If interested in helping please contact the package author.

## LISCENSE Example
Copyright (c) 2011, under the Simplified BSD License.  
For more information on FreeBSD see: http://www.opensource.org/licenses/bsd-license.php  
All rights reserved.

# Documentation

## Documenting Example
```{r simple-ex}
#' simple.ex

#' Simple Example

#' This is a simple example of a function

#' @aliases simple.ex

#' @author Jared P. Lander

#' @export simple.ex

#' @param x A numeric

#' @param y A second numeric

#' @return x times y

#' @examples

#' simple.ex(5, 3)
simple.ex <- function(x, y)
{
    return(x * y)
}
```

## The Help File
    \name{simple.ex}
    \alias{simple.ex}
    \title{within.distance}
    \usage{simeple.ex(x, y)}
    \arguments{
        \item{x}{A numeric}
        \item{y}{A second numeric}
    }
    \value{x times y}
    \description{Compute distance threshold}
    \details{This is a simple example of a function}
    \author{Jared P. Lander}
    \examples{
        simple.ex(3, 5)
    }


```{r tab-example,results='asis',include=FALSE,eval=FALSE}
require(xtable)
myTab <- data.frame(A=1:5, B=5:1)
print(xtable(myTab), "html", caption="MY CAPTION", caption.placement="top", include.colnames=FALSE, include.rownames=FALSE, html.table.attributes=getOption("xtable.html.table.attributes", "border=0"))
```

## S3 Methods
```{r s3-example,eval=FALSE}
#' print.myClass
#' @aliases print.myClass
#' @method print myClass
#' @S3method print myClass
#' @export print.myClass
#' @param x Simple object
#' @param \dots Fi=urther arguments to be passed on
#' @return The top 5 rows of \code{x}
print.myClass <- function(x, ...)
{
    class(x) <- "list"
    x <- as.data.frame(x)
    print.data.frame(head(x, 5))
}
```

# Building Your Package

## Document Your Package
```{r document-package,eval=TRUE}
require(devtools)
document(pkg="pkg", clean=TRUE)
```

## Build Your Package
Linux/Mac

    $ R CMD build simple

Windows

    # Create tar
    $ R CMD build simple
    # create zip
    $ R CMD INSTALL --build simple

Devtools
```{r build-package,results='hide',eval=FALSE}
build(pkg="pkg", binary=TRUE)
```

## Check Your Package
Linux/Mac/Windows

    $ R CMD check simple_1.0.0.tar.gz

Devtools
```{r check-package,eval=FALSE}
check(pkg="pkg")
```

_Warnings_ and _Errors_ must be fixed before submitting to CRAN

## Submit Your Package
- Upload to ftp://cran.r-project.org/incoming

- Email ligges\<at\>statistik\<dot\>tu-dortmund\<dot\>de  
_and_  
cran\<at\>r-project\<dot\>org  

- with 'CRAN Upload: simple 1.0.0' in the subject

# Dealing with C++

## Rcpp
Is your friend

Use it

## The R Function
```{r cpp-example-r,eval=FALSE}
#' vect.add

#' @aliases vect.add

#' @export vect.add

#' @useDynLib simple

vect.add <- function(x, y)
{
    .Call("vector_add", x, y, PACKAGE="simple")
}
```

## The C++ Function
```Cpp
#include <Rcpp.h>
using namespace Rcpp;

RcppExport SEXP vector_add(SEXP x, SEXP y)                                 
{
    NumericVector x_(x); NumericVector y_(y);
    NumericVector result(x_.size());
    // for each element add the two cells
    for(int i=0; i<x_.size(); ++i)
    {
        result[i] = x_[i] + y_[i];
    }

    return(wrap(result));
}
```

## Simpler C++
```Cpp
#include <Rcpp.h>
using namespace Rcpp;

RcppExport SEXP vector_add(SEXP x, SEXP y)                                 
{
    NumericVector x_(x); NumericVector y_(y);
    
    return(wrap(x_ + y_));
}
```

## Building
Same commands as with plain R

# Remember
## You need...
- Proper Folder Structure
- Proper Files
- Documentation (with roxygen)
- Build & install from within R
- Publish to CRAN

# Questions?

## Built With...
- [RStudio](http://www.rstudio.org)
- [knitr](http://yihui.name/knitr/)
- [Pandoc](http://johnmacfarlane.net/pandoc/README.html)

<!--- pandoc code:  pandoc -s -S --self-contained -t dzslides PackageBuilding.md -o PackageBuildingSlides.html --slide-level=2 --->
