%\VignetteDepends{}
%\VignetteIndexEntry{}
%\VignettePackage{AdvancedR2011}

\documentclass{article}
\usepackage{amsfonts}
\usepackage{BioconductorVignette}
\SweaveOpts{keep.source=TRUE,width=9,height=8,eps=FALSE,include=FALSE}

\title{Building Packages: Self-Study Exercises}
\author{Chao-Jen Wong \\ Fred Hutchinson Cancer Research Center}
\date{17-18 February, 2011}


\begin{document}
\maketitle
<<setup, echo=FALSE>>=
options(width = 40)
@ 

\section{Introduction}
This document covers topics of \R{} source packages, including  creating a
package, using \R{} tools, namespace and \R{} documentation (Rd). 

Throughout the workshop, you will develop tools for facilitating the
manipulation and processing of GWAS data during the lab hour following the
lecture. The exercises in this document  lead you to build, extend
and polish a package named \Rpackage{StudentGWAS} containing tools and
functions, classes and methods that you have developed from each
session. 

\section{Creating a package}
When developing software in R, a package is a better way to organize your code
and to share the software with others. This section introduces package
structure and construction of a simple package of limited capability.  

An \R{} source package consists of a top-level directory containing
\texttt{DESCRIPTION} and \texttt{NAMESPACE}
files and subdirectories \texttt{R, data, inst, man, src, demo} and
\texttt{tests}.  The subdirectories may contain optional files such as
\texttt{ChangeLog}, \texttt{NEWS}, \texttt{LICENSE}, \texttt{COPYING},
\texttt{CITATION}, \texttt{configure} and \texttt{cleanup}.  

To create a package, you can manually create the structure and place the
essential files, \R{} codes, documentation and data sets in appropriate
places. Alternatively, the \R{} function \Rfunction{package.skeleton()} 
creates a package skeleton and initial documentation files. Consult
the \Rfunction{package.skeleton()} help page for more  details. 

\begin{Ext} % exercise
  Create a package named \Rpackage{StudentGWAS} containing a simple object
  \Robject{.fapply}. 
  \begin{itemize}
    \item Make sure that the \Robject{.fapply} function you have created
      during the \emph{Efficient R Programming} session is accessible on your
      \R{} session. 
    \item Create the package with the following comment: 
      \begin{verbatim}
package.skeleton(name="StudentGWAS", list=c(".fapply"), 
                 namespace=TRUE)
      \end{verbatim}
     \item What got created?
   \end{itemize}
\end{Ext}



\subsection{The DESCRIPTION file}
The \texttt{DESCRIPTION} file contains basic information about the
package. The `Package', `Version', `License', `Description', `Title',
`Author', and `Maintainer' fields are mandatory. The `Depends', `Imports',
`Suggests' and `biocViews' fields are recommended for packages contributed to
Bioconductor. All other fields such as `LazyLoad', `LazyData', `URL' and
etc. are optional.

The 'Package' field gives the name of the package. The 'Version' field gives
the version of the package. The conventional version format for Bioconductor
packages is the form of x.y.z, where x, y and z are integers. 

\begin{Ext}
  Edit the DESCRIPTION file in the \Rpackage{StudentGWAS} package and fill out
  the mandatory fields. Specify the `License' field as Artistic-2.0.
\end{Ext}

\subsection{The NAMESPACE file}
\R{} supports namespaces for packages. The way to specify a namespace
for a package is to place the \texttt{NAMESPACE} file in the top directory of
the package.  In the \texttt{NAMESPACE} file, specify which
variables in the package are exported and which variables are
imported from other packages. It is strongly recommended to use namespaces for
various reasons. Most importantly, it helps to avoid naming 
collisions and to clarify what is public and private and the relationship of
your package with other packages. 

The default \texttt{NAMESPACE} file of your \Rfunction{StudentGWAS} package
is
\begin{verbatim}
exportPattern("^[[:alpha:]]+")
\end{verbatim}
which means that all visible objects (whose names starts with a letter) are
exported.  Note that the \Robject{.fapply} object at this point would be
invisible (unexported). 
When developing a more complicated package, you might want to make some objects
private and some public.   

Adding a namespace affects the search hierarchical order.  Having a namespace
for a package guarantees it comes first in the search, followed by the imports, then
the base namespace, and then the normal search path.

\begin{Ext}
  Export objects can be specified using the \Rfunction{export} directive in
  the \texttt{NAMESPACE} file. 
  Upon to this point, you  have the \Rpackage{StudentGWAS} package 
  containing the object \texttt{.fapply} in the R subdirectory. To
  make this object public, use a  directive of the form 
  \begin{verbatim}
export(.fapply)
  \end{verbatim}
  to specify that \Rfunction{.fapply} is to be exported.
  
\end{Ext}

% how to access unexported objects?
\begin{Ext}
  At the end of this lab, please download the first snapshot of the 
  \Rfunction{StudentGWAS} package from
  \url{http://bioconductor.org/course-packages/src/contrib/StudentGWAS_0.1.0.tar.gz}
\end{Ext}

\section{\R{} tools}
R provides a set of tools to manage packages. These tools are usually accessed
from a command shell. Listed below are the shell commands for building,
checking and installing packages. 

The shell command
\begin{verbatim}
$ R CMD INSTALL pkg
\end{verbatim}
carries out package installation.

The shell command
\begin{verbatim}
$ R CMD INSTALL --binary pkg
\end{verbatim}
installs and produce a binary source archive (*.zip) for use on Windows only.

The shell command
\begin{verbatim}
$ R CMD build pkg
\end{verbatim}
packages up the package source and builds an archive file.

To check whether the package works correctly, use the shell command
\begin{verbatim}
$ R CMD check pkg (or pkg.tar.gz)
\end{verbatim}
This command runs a set of checks for issues such as \R{} files syntax errors,
package dependencies, completeness and correctness of documentation,
consistency of method definition, and etc. See the \emph{Writing R Extensions}
manual for more details. 

Note that those commands takes a variety of shell-style options. For example,
\begin{verbatim}
$ R CMD check --no-docs
\end{verbatim}
tells \R{} not to check and execute the examples in the documentation.

To obtain information for a particular tool, use
\begin{verbatim}
$ R CMD operation --help
\end{verbatim}
where \emph{operation} is an \R{} shell tool.

For Windows users, you should install \texttt{Rtools} from
\url{http://www.murdoch-sutherland.com/Rtools/} to get Unix-like command
line tools, Perl, MinGW gcc compilers and some other files needed to build
\R{} itself.
% exercise include using R CMD build, check and INSTALL or INSTALL --build
\begin{Ext}
Use \R{} shell tools to build, check and install the \Rpackage{StudentGWAS}
package. 
\end{Ext}


%-----------------------------------------------------------------
%-------------------------- after Marc's session -----------------

\section{R documentation (Rd)}
The help pages for R objects are written in \R{} documentation (Rd) format.
Rd is a simple markup language resembling \LaTeX{}. An Rd file can be
translated into a number of forms, including \LaTeX{}, HTML, PDF and plain
text. 

% Rd skeleton here
Below is a simplified version of the Rd file that documents the \Rfunction{sd}
function.

\begin{verbatim}
\name{sd}
\alias{sd}

\title{Standard Deviation}

\description{
This function computes the standard deviation of the values in x. If
na.rm is TRUE then missing values are removed before computation
proceeds. If x is a matrix or a data frame, a vector of the standard
deviation of the columns is returned. 
}

\usage{
sd(x, na.rm=FALSE)
}

\details{
Like \code{var} this uses denominator n-1.
The standard deviation of a zero-length vector (after removal of \code{NA}s if
\code{na.rm} = \code{TRUE}) is not defined and gives an error. The
standard deviation of a length-one vector is \code{NA}.  
}

\examples{
sd(1:2)^2
}
\end{verbatim}

There are several types of Rd documentation depending on the type of objects
being documented. These types are:

\begin{description}
   \item[Functions] The Rd document for functions must specify sections for
     describing the usage, argument, value, and example, as shown
     above. Multiple functions that are related and similar can be described
     in one Rd file. The function \Rfunction{prompt()} can be used to
     construct an outline of Rd files for documenting the functions. The
     \Rfunction{check()} function checks the conformity of the documentation and
     the actual functions.
     
  \item[Description of Package] A package should have an Rd file describing
    the general purpose and contents of the package. The alias section of the
    Rd file should contain \texttt{pkg-package},
    e.g. \texttt{utils-package} for the \Rpackage{utils} package such that the
    help page of the package can be invoked in \R{} session as
    \Rfunction{package?pkg}. 
    \begin{verbatim}
\name{pkg-package}
\alias{pkg-package}
\docType{package}
.
.
.
\keyword{ package }
    \end{verbatim}
    The help page of a package is invoked in an \R{} session as
    \Rfunction{package?pkg}. The function \Rfunction{promptPackage()} helps 
    creating a skeleton of the Rd file for package description. 

  \item[S4 classes and methods] The function \Rfunction{promptClass()} generates
    an outline of the class documentation, and \Rfunction{promptMethods()}
    generate an outline of methods for a generic function.  The syntax for
    specifying 
    documentation for this type of topic can be more tedious then other
    topics. (See the \emph{Writing R Extensions} manual for more information.)
    The help packages for classes ($\mathcal{C}$) and methods ($\mathcal{M}$)
    can be invoked in \R{} as \Rfunction{class?$\mathcal{C}$} and
    \Rfunction{method?$\mathcal{M}$}, respectively. 

  \item[Data sets] The Rd file documenting data sets does not need to include
    sections as \texttt{argument} and \texttt{value}. The function
    \Rfunction{promptData()} can be use to generate a shell of documentation
    for a data set.
    
\end{description}

\begin{Ext}
  In the previous lab, we have created three functions, \Rfunction{getSnps},
  \Rfunction{getSubjects} and \Rfunction{getKEGGSnps}. Here, we construct an
  Rd file named \texttt{SQLiteFunctions.Rd} documenting one or more of three
  functions. 
  \begin{itemize}
    \item Use \Rfunction{prompt} to construct a prototype Rd file ready for
      manual editing.
      \begin{verbatim}
prompt(getSnps, filename=''SQLiteFunctions.Rd'' force.function=TRUE) 
      \end{verbatim}
    \item Edit the Rd file and move it to an appropriate place in the
      \Rpackage{StudentGWAS} package.
  \end{itemize}
\end{Ext}


The shell commend \texttt{R CMD check} checks the
syntax and executes the examples in the Rd files and translate the files into a
variety of formats, including \LaTeX{}, HTML and plain text. A couple shell
commands can help to carry out translation of a single Rd file into a particular
format.:

\begin{itemize}
  \item If you have \LaTeX{} installed, you can use the shell commend
\begin{verbatim}
$ R CMD Rd2dvi --pdf foo.Rd
\end{verbatim}
to convert an Rd file to PDF format. 

  \item To convert an Rd file to HTML, use the shell command
\begin{verbatim}
R-dev CMD Rdconv --type='html' --output=foo.html foo.Rd
\end{verbatim}
\end{itemize}

The utility function \Rfunction{checkRd} can check adequacy and accuracy of the
documentation. The \Rpackage{tools} package also provides a set of functions
for converting Rd into different formats. Consult the help page of
\Rfunction{tools::Rd2HTML} for details. 


See \emph{Guidelines for Rd files}
(\url{http://developer.r-project.org/Rds.html} for detailed guidelines for
writing Rd files.  For detailed syntax and technical discussion, see
\emph{Parsing Rd files} (\url{http://developer.r-project.org/parseRd.pdf}). 


\begin{Ext}
  At the end of this lab, please download the second snapshot of the 
  \Rfunction{StudentGWAS} package from
  \url{http://bioconductor.org/course-packages/src/contrib/StudentGWAS_0.2.0.tar.gz}
\end{Ext}

\end{document}
