---
title: "Step by step guide for creating a package that depends on RStan"
author: "Stefan Siegert, Jonah Gabry, and Ben Goodrich"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    toc: true
params:
  EVAL: !r identical(Sys.getenv("NOT_CRAN"), "true")
vignette: >
  %\VignetteIndexEntry{Step by step guide}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, SETTINGS-knitr, include=FALSE}
stopifnot(require(knitr))
opts_chunk$set(
  comment=NA,
  eval = params$EVAL
)
```

## Introduction

In this vignette we will walk through the steps necessary for creating an 
R package that depends on Stan by creating a package with one function 
that fits a simple linear regression. Before continuing, we recommend that you first read the other vignette [_Guidelines for Developers of R Packages Interfacing with Stan_](http://mc-stan.org/rstantools/articles/developer-guidelines.html).

## Creating the package skeleton

To start off, we use `rstan_package_skeleton` to initialise a bare-bones
package directory. The name of our demo package will be __rstanlm__; it will fit
a simple linear regression model using Stan. 

```{r, eval=FALSE}
library("rstantools")
rstan_package_skeleton(path = 'rstanlm')
```
```{r, echo=FALSE,warning=FALSE}
library("rstantools")
td <- tempdir()
PATH <- file.path(td, "rstanlm")
rstan_package_skeleton(path = PATH, rstudio=FALSE, open=FALSE)
```

If we had existing `.stan` files to include with the package we could use the 
optional `stan_files` argument to `rstan_package_skeleton` to include them. 
Another option, which we'll use below, is to add the Stan files once the 
basic structure of the package is in place. 

We can now set the new working directory to the new package directory and view the contents. (Note: if using RStudio then by default the newly created project for the package will be opened in a new session and you will not need the call to `setwd()`.)


```{r, eval=FALSE}
setwd("rstanlm")
list.files(all.files = TRUE)
```
```{r, echo=FALSE}
list.files(PATH, all.files = TRUE)
```

```{r, eval=FALSE}
file.show("DESCRIPTION")
```
```{r, echo=FALSE}
DES <- readLines(file.path(PATH, "DESCRIPTION"))
cat(DES, sep = "\n")
```
Some of the sections in the `DESCRIPTION` file need to be edited by hand
(`Title`, `Author`, `Maintainer`, and `Description`), but
`rstan_package_skeleton()` has added the necessary packages and versions to
`Depends`, `Imports`, and `LinkingTo`. It also added the `SystemRequirements`
and `NeedsCompilation` fields.

## Read-and-delete-me file

Before deleting the `Read-and-delete-me` file in the new package
directory make sure to read it because it contains some 
important instructions about customizing your package:

```{r, eval=FALSE}
file.show("Read-and-delete-me")
```
```{r, echo=FALSE}
cat(readLines(file.path(PATH, "Read-and-delete-me")), sep = "\n")
```

You can move this file out of the directory, delete it, or list it in the
`.Rbuildignore` file if you want to keep it in the directory.

```{r, eval=FALSE}
file.remove('Read-and-delete-me')
```
```{r, echo=FALSE}
file.remove(file.path(PATH, 'Read-and-delete-me'))
```


## Stan files

Our package will call RStan's `sampling` method to use MCMC to fit a simple
linear regression model for an outcome variable `y` with a single predictor `x`.
After writing the necessary Stan program, the file should be saved with a
`.stan` extension in the `src/stan_files/` subdirectory. We'll save the
following program to `src/stan_files/lm.stan`:

```
// Save this file as src/stan_files/lm.stan
data {
  int<lower=1> N;
  vector[N] x;
  vector[N] y;
}
parameters {
  real intercept;
  real beta;
  real<lower=0> sigma;
}
model {
  // ... priors, etc.
  
  y ~ normal(intercept + beta * x, sigma);
}
```

```{r, include=FALSE}
stan_prog <- "
data {
  int<lower=1> N;
  vector[N] x;
  vector[N] y;
}
parameters {
  real intercept;
  real beta;
  real<lower=0> sigma;
}
model {
  // ... priors, etc.
  
  y ~ normal(intercept + beta * x, sigma);
}
"
cat(stan_prog, file = file.path(PATH, "src", "stan_files", "lm.stan"))
```

The `src/stan_files` subdirectory can contain additional Stan programs if
required by your package. During installation, all Stan programs will be
compiled and saved in the list `stanmodels` that can then be used by R function
in the package. The rule is that the Stan program compiled from the model code
in `src/stan_files/foo.stan` is stored as list element `stanmodels$foo`.

## R files

We next create the file `R/lm_stan.R` where we define the function `lm_stan` in
which our compiled Stan model is being used. A comment block in
[__roxygen2__](https://CRAN.R-project.org/package=roxygen2) syntax
ensures that the function has a help file and that it is added to the NAMESPACE:

```{r}
# Save this file as `R/lm_stan.R`

#' Bayesian linear regression with Stan
#'
#' @export
#' @param x Numeric vector of input values.
#' @param y Numberic vector of output values.
#' @param ... Arguments passed to `rstan::sampling` (e.g. iter, chains).
#' @return An object of class `stanfit` returned by `rstan::sampling`
#'
lm_stan <- function(x, y, ...) {
  standata <- list(x = x, y = y, N = length(y))
  out <- rstan::sampling(stanmodels$lm, data = standata, ...)
  return(out)
}
```


```{r, include=FALSE}
Rcode <- "
#' Bayesian linear regression with Stan
#'
#' @export
#' @param x Numeric vector of input values.
#' @param y Numberic vector of output values.
#' @param ... Arguments passed to `rstan::sampling`.
#' @return An object of class `stanfit` returned by `rstan::sampling`
lm_stan <- function(x, y) {
  out <- rstan::sampling(stanmodels$lm, data=list(x=x, y=y, N=length(y)))
  return(out)
}
"
cat(Rcode, file = file.path(PATH, "R", "lm_stan.R"))
```

The top-level package file `R/rstanlm-package.R` has already been created by
`rstan_package_skeleton()` but needs to be modified to decribe the functionality
of our package:

```{r, eval=FALSE}
file.show(file.path("R", "rstanlm-package.R"))
```
```{r, echo=FALSE}
cat(readLines(file.path(PATH, "R", "rstanlm-package.R")), sep = "\n")
```

The description section needs to be manually edited but the necessary
__roxygen2__ tags for specifying important parts of the `NAMESPACE` file have
already been included.


## Documentation

To update the `NAMESPACE` file and the rest of the documentation to include
`lm_stan` we need to regenerate the documentation using `roxygen2::roxygenise` (or `devtools::document`): 

```{r, eval=FALSE}
roxygen2::roxygenise(clean=TRUE)
```
```{r, echo=FALSE}
roxygen2::roxygenise(PATH, clean=TRUE)
```


## Install and use

Finally, the package can be installed:

```{r,eval=FALSE}
devtools::install(local=FALSE)
```
```{r,echo=FALSE, results="hide"}
devtools::load_all(PATH, recompile=TRUE)
```

The argument `local=FALSE` is necessary if you want to recompile the Stan
models. If you only made a small change to the R code or the documentation, you
can set `local=TRUE` to speed up the process.

The package can now be loaded and used like any other R package:

```{r, eval=FALSE}
library("rstanlm")
```

```{r}
fit <- lm_stan(y = rnorm(10), x = rnorm(10), iter = 500)
print(fit)
```

```{r, echo=FALSE}
unlink(PATH, recursive = TRUE)
```

## Links

* [R packages](http://r-pkgs.had.co.nz/) by Hadley Wickham provides a solid
foundation in R package development as well as the release process.

* [_Guidelines for Developers of R Packages Interfacing with Stan_](http://mc-stan.org/rstantools/articles/developer-guidelines.html)

* Ask a question at the [Stan Forums](http://discourse.mc-stan.org/)

