%\VignetteIndexEntry{First Steps with R}
%\VignettePackage{HTSandGeneCentricLabs}
\documentclass{article}
\usepackage{BioconductorVignette}
%\include{labheader}

\begin{document}

\SweaveOpts{keep.source=TRUE,width=9,height=8,eps=FALSE,include=FALSE}

\title{First Steps with \R}
\author{Seth Falcon \and Martin Morgan}
\maketitle

\tableofcontents

<<setup, echo=FALSE>>=
options(width=60)
olocale = Sys.setlocale(locale="C")
vers <- R.Version()
vers <- paste(vers$major, vers$minor, sep = ".")
@

\section{Install \R}

The first step is to select a nearby CRAN mirror site from the list at
\url{http://cran.r-project.org/mirrors.html}.  You should now have a
web browser open displaying the main page of your selected CRAN
mirror.

Now follow the instructions below appropriate for your operating
system:

\begin{description}
  \item[Windows]

    \begin{enumerate}
      \item Click the \textit{Windows} link.
      \item Click the \textit{base} link for ``Binaries for
        base distribution (managed by Duncan Murdoch)'' and then
        download the main link for \textit{Download R \Sexpr{vers} for
        Windows}.
      \item Double-click the file you downloaded
            (\textit{R-\Sexpr{vers}-win32.exe}) and follow the
            installation prompts.  You can accept all of the default
            values.

      \item Start \R by double-clicking on the \R icon on your desktop
            or selecting the entry from the Start, Program Files menu.
      \end{enumerate}

  \item[Mac OS X]

    \begin{enumerate}
      \item Click the \textit{MacOS X} link.
      \item Download the first link with name
        \textit{R-\Sexpr{vers}.pkg}.  This is a universal binary for OS X
        10.5 and higher.  If you have an older version of OS X, read the
        details on that page to determine which package to download.
      \item Double-click the downloaded pkg file and follow the
            installation prompts.  You can accept all of the default
            values.

      \item Start \R by clicking the \textit{R.app} icon in your
            Applications folder.
    \end{enumerate}

  \item[Linux]
    \begin{itemize}

    \item Your Linux distribution's package manager may already have
            the latest version of \R available (R-\Sexpr{vers}).  If
            not there may be a precompiled binary package available.
            Click the \textit{Linux} link on CRAN and follow the
            instructions based on your distribution.

      \item You can build from source instead of using a precompiled
            binary.  In this case, download the source package from
            the main page of your CRAN mirror:
            \textit{R-\Sexpr{vers}.tar.gz}.  Installation instructions
            can be found here:
            \url{http://cran.fhcrc.org/doc/manuals/R-admin.html}

      \item If \texttt{R} is not in your \texttt{PATH}, add it.  Then
            start \R with the \texttt{R} command.

    \end{itemize}
\end{description}


\section{Atomic Vectors -- \R's Basic Types}

There are six basic data types in \R that are always represented as
\Rclass{vector}s (see Table~\ref{tab:types}).  A vector is a
one-dimensional array of items of the same type.  In \R, these vectors
are called \textit{atomic vectors} because they cannot be split into
individual items; single items are represented as
vectors of length one.

\begin{table}[htb]
\begin{center}
\begin{tabular}{ll}
  type      & example \\ \hline
  logical   & \code{TRUE}, \code{FALSE} \\
  integer   & \code{0L}, \code{1L} \\
  numeric   & \code{1}, \code{3.14} \\
  complex   & \code{1+1i} \\
  character & \code{"a"} \\
  raw       & \code{as.raw(255)} \\
\end{tabular}
\label{tab:types}
\caption{The atomic vector data types in \R.  The ``L'' suffix
indicates an integer literal in \R code; digits with no decimal point
are interpreted as type \Rclass{numeric} (real).}
\end{center}
\end{table}

Since ``everything's a vector''\footnote{Well, almost everything.  \R{}
also has \Rclass{list}s, \Rclass{environment}s, S3, and S4 classes
none of which are vectors}, most functions in \R{} are
\textit{vectorized}.  Vectorized functions accept vectors as input and
perform an action element-wise on the input.  Consider the following
example:

<<simpleVectorized>>=
## length, width, and height measurements
L <- c(1.2, 4.3, 2.3, 3)
W <- c(13.8, 22.4, 18.1, 17)
H <- c(7, 7, 10, 3.4)
volume <- L * W * H
volume
total_length <- sum(L)
total_length
@

The example above defines three \Rclass{numeric} vectors representing
length, width, and height measurements of four objects.  Vector
literals are constructed using the \Rfunction{c} function which should
be given a comma separated list of items of the same type to
concatenate into a vector.  The assignment operator in \R{} is \code{<-}
although you can also use \code{=}.  Comments begin with \code{\#} and
continue to the end of the line.  The volume of each object is
computed by vectorized multiplication using \Rfunction{*} which
operates element-wise.  The \Rfunction{sum} function accepts a vector
and returns a new vector of length one containing the sum of the
elements of the input.

Start up a new \R{} session and try the following exercises:

\begin{Ext}
  Create a vector representing the radii of three circles with lengths
  5, 10, and 20.  Use \Rfunction{*} and the built-in constant
  \Robject{pi} to compute the areas of the three circles.  Then
  subtract 2.1 from each radius and recompute the areas.
\end{Ext}
\begin{Solution}
<<circleSolution>>=
circles <- c(5, 10, 20)
# areas are:
pi * circles * circles
# you could also use ^
pi * circles^2
# reduce radii by 2.1
pi * (circles - 2.1)^2
@
\end{Solution}

\begin{Ext}
  Creating regular numeric sequences is a common task in statistical
  computing.  You can use the \Rfunction{seq} function to create
  sequences as well as a shorthand \Rfunction{:} (e.g. \code{1:10}).
  \begin{enumerate}
    \item Read the help page for \Rfunction{seq} by entering
          \code{help(seq)}.
    \item Generate a decreasing sequence from 50 to 1, then another
          sequence from 1 to 50.  See if you can understand the
          meaning of the \code{[i]} prefix that \R{} uses to print
          vectors.
    \item Use \Rfunction{seq} to generate a sequence of the even
          integers between one and ten.
  \end{enumerate}
\end{Ext}

\begin{Solution}
<<simpleSeq>>=
## sequences from 100 to 1 and 1 to 100
50:1 # or seq(100, 1)
1:50 # or seq(1, 100)
## the [i] prefix tells you the index of the first
## item on the current line within the vector
## being displayed.

## even integers
seq(2, 10, 2)
@
\end{Solution}

\begin{Ext}
  All \R{} functions have a manual page that you can access via
  \code{help(funcName)}, or the shorthand \code{?funcName}.  Most
  manual pages include an example section which you can execute in
  your session by calling \code{example(funcName)}.  Run the examples
  for the \Rfunction{paste} function.  Use \Rfunction{paste} to create
  a character vector of length one that looks like \code{"id-1, id-2,
  id-3"}.
\end{Ext}
\begin{Solution}
<<pasteExample>>=
example(paste)
paste("id", 1:3, sep="-", collapse=", ")
@
\end{Solution}

\section{Subsetting Vectors}

Next we will take a tour of the ways that one can slice, extract,
index, subset and otherwise get data out of vectors in \R.  We will
use the following vector \Robject{v} as an example.

<<exampleVect>>=
## You can name the elements of a vector
## The names do not have to be unique, but
## often you will want them to be.
v <- c(a = 1.1, b = 2, b = 100, c = 50, d = 60)
v
@

\subsection{Integer subsetting}

<<integerSubsetting>>=
v[1]
v[length(v)]
v[3:5]
v[c(1, 1, 4, 4)]
@
\begin{Ext}
  Create an integer vector \Robject{i} that can be used to subset
  \Robject{v} such that it will output the elements of \Robject{v} in
  decreasing order.  For the general case, read the help pages for
  \Rfunction{order} and \Rfunction{sort}.
\end{Ext}
\begin{Solution}
<<subsettingInOrder>>=
## you need the L's if you want an _integer_ vector,
## otherwise you get a numeric (double) vector.
v[c(3L, 5L, 4L, 2L, 1L)]
v[order(v, decreasing = TRUE)]
@
\end{Solution}

Zero values are ignored in integer subsetting and negative values can
be used to exclude elements (positive and negative indices cannot be
mixed).

<<negAndZeroSub>>=
v[c(1, 0, 0, 0, 0, 3)]
v[-2]
v[seq(1, length(v), 2)]
v[-seq(1, length(v), 2)] # note the '-' sign

## two other special cases
v[]
v[integer(0)]
@

\subsection{Logical subsetting}

In a subset expression \code{v[i]} when \Robject{i} is a logical
vector (\code{TRUE}/\code{FALSE}) with the same length as \Robject{v}
we refer to it as \textit{logical subsetting}.  Values of \Robject{v}
that align with a \code{TRUE} in \Robject{i} are selected.

<<logicalSubset>>=
v[c(TRUE, FALSE, FALSE, FALSE, FALSE)]
v > 5
v[v > 5]
v[!(v > 5)] # or (v <= 5)
v[(v > 5) & (v < 90)] # element-wise AND
v[(v < 5) | (v > 90)] # element-wise OR
v[v == 100]
@

\begin{Ext}
  The names of a vector can be obtained using \Rfunction{names}.
  Create a logical vector that has a \code{TRUE} for all names equal
  to ``b''.  Use this logical vector to extract all elements of
  \Robject{v} with a name of ``b''.
\end{Ext}

\begin{Solution}
<<useNamesEquals>>=
v[names(v) == "b"]
@

\end{Solution}

\subsection{Subsetting by name}

Finally, in the case of a named vector, you can use the names to
select elements.  If the vector has non-unique names, the first
element to match is returned.

<<subsetByName>>=
v["c"]
v[c("d", "a")]
v["b"] # only get first match
@

\begin{Ext}
  Use \Rfunction{sample} to randomly select three names of \Robject{v}
  and then use the result to extract the corresponding elements of
  \Robject{v}.
\end{Ext}
\begin{Solution}
<<sampleNames>>=
set.seed(5644L)
i <- sample(names(v), 3)
v[i]
@
\end{Solution}

\section{Matrix, \Rclass{data.frame}, and 2-D Subsetting}
\label{sec:data.frames}
After vectors, two very common data structures in \R{} are the
\Rclass{matrix} and the \Rclass{data.frame}.  A \Rclass{matrix} is a
two-dimensional vector.  Like vectors, all elements share a common
type.  The \Rclass{data.frame} class groups together a set of vectors
(columns) of the same length.  A \Rclass{data.frame} is analogous to a
table in a relational database, and is used to represent statistical
data sets where each row represents a sample and each column an
attribute of the sample.  The columns can be of different types, but
within a column all elements are the same type.

Subsetting a matrix or \Rclass{data.frame} is similar to subsetting
vectors, except that two arguments are given to the \Rfunction{[}
operator.  All of the subsetting approaches (integer, logical,
character) that you've used with vectors can be used with matrices and
\Rclass{data.frame}s.  Consider the following examples and then
explore the exercises that follow.

<<matrixExtample>>=
m <- matrix(1:25, ncol = 5,
            dimnames = list(letters[1:5], LETTERS[1:5]))
m

## extract an element
m[3, 1]

## subset the matrix
m[1:3, 1:3]

## empty index argument means
## select all of the dimension
m[ , 2] # 2nd column all rows
m[4, ] # 4th row all columns
@

\begin{Ext}
  Create a new matrix from \Robject{m} by removing the second row and
  the fourth column.  \textit{Hint: use negative indices.}
\end{Ext}
\begin{Solution}
<<matrixRemoveRowCol>>=
m[-2, -4]
@
\end{Solution}

\begin{Ext}
  Subset \Robject{m} such that you keep only rows where the value in
  the ``D'' column is greater than 17.
\end{Ext}
\begin{Solution}
<<matrixgt17>>=
d_gt17 <- m[ , "D"] > 17
m[d_gt17, ]
@
\end{Solution}

\begin{Ext}
  Find the element-wise product of rows ``b'' and ``d''.
\end{Ext}
\begin{Solution}
<<bdprod>>=
m["b", ] * m["d", ]
@
\end{Solution}


We'll use the \Robject{Indometh} data set that comes with \R{} to work
some examples with the \Rclass{data.frame} class.  If you want to know
what this data represents, call \code{help(Indometh)}.

<<dataFrameExtample>>=
## load a dataset that comes with R
data(Indometh)
df <- Indometh # use a shorter name
class(df)
dim(df)
names(df)

df[1:3, ]

## The following are all ways of
## extracting the time column
##
## df[ , "time"]; df[, 2]
## df[["time"]]; df[[2]]
## df$time
identical(df[, 2], df$time)
@

\begin{Ext}
\begin{enumerate}
  \item Extract the rows of \Robject{df} that contain data for subject 2.
  \item Extract the rows for time point 0.50.
  \item Which subjects had a concentration greater than 0.38 at time
        point 2.0?
\end{enumerate}
\end{Ext}
\begin{Solution}
<<dfSubsetting>>=
## Subject 2
head(df[df$Subject == "2", ])
## time point 0.50
head(df[df$time == 0.50, ])
## conc > 0.38 at time point 2.0
df[df$time == 2.0 & df$conc > 0.38, ]
@
\end{Solution}

\section{Lists}

A limitation of \R's atomic vectors is that all items must be of the
same type.  \R{} provides two data types for organizing arbitrary
collections of \R{} objects: \Rclass{list} and \Rclass{environment}.
Both are \textit{recursive} data structures meaning that a list can
contain other lists (as well as other types) and an environment can
contain other environments (and other types).  Lists are discussed
below.  See Section~\ref{sec:env} for an introduction to
\Rclass{environment}.


In Section~\ref{sec:data.frames} you worked with a \Rclass{data.frame}
which at its core is a \Rclass{list} of vectors.  In fact,
except for the 2-dimensional subsetting, you will see many
similarities between \Rclass{list} subsetting and accessing the
columns of a \Rclass{data.frame}\footnote{In many cases, the
underlying code is the same: a \Rclass{data.frame} \textit{is a}
\Rclass{list}.}

<<listExamples>>=
things <- list(a = 1:3, b = c("X", "Y"),
               uspaper = list(length = 11, width = 8.5, units = "in"),
               eupaper = list(length = 297, width = 210, units = "mm"),
               TRUE)
things

names(things)
length(things)
@

List elements, like items in a vector, can be named, but this is not
required.  In the example above, all elements of \Robject{things} are
named except for the last element, a logical vector of length one
containing the value \Robject{TRUE}.

You can extract the element names of a list using \Rfunction{names}
just as you can with a vector (recall that for a \Rclass{data.frame},
\Rfunction{names} returns the names of the columns).

\subsubsection{Extracting elements from a list}

You can extract \textit{elements} of a list using double square
brackets as shown below.

<<listElExtract>>=
## by position using [[
things[[4]]
## by name using [[
things[["b"]]
## by name using $
things$a
@

%% Details: $ doesn't evaluate
%%          recursive extract:
%%          things[[c("uspaper", "width")]]

\subsubsection{Subsetting lists}

List subsetting is achieved using single square brackets which will
always return a new list.

<<listSubsetting>>=
## by index
things[2]
things[c(1, 5)]
## negative indices remove just like vectors
things[-c(3, 4)]
## by name
things[c("a", "b")]
## logical works too
hasLenTwo <- sapply(things, function(x) length(x) == 2)
hasLenTwo
things[hasLenTwo]
@

\begin{Ext}
  Explain the difference between \code{things[["uspaper"]]} and
  \code{things["uspaper"]}.
\end{Ext}

\begin{Solution}
  Using double square brackets extracts an element from the
  \Robject{things} list, in this case a list with three elements.
  Single square brackets subsets the \Robject{things} list and returns
  a list of length one, its first and only element is the list of
  length three returned by the double bracket expression.
\end{Solution}

\begin{Ext}
  Extract the ``uspaper'' and ``eupaper'' lists from \Robject{things}
  and assign each to a variable.  Subset each list to remove the
  element with name ``units''.  Convert each resulting two-element
  list to a numeric vector using \Rfunction{as.numeric}.  Convert the
  uspaper values to millimeters by multiplying by 25.4.  Finally, use
  \Rfunction{prod} to compute the areas of the two paper sizes.  Can
  you compute each area in a one-liner without assigning temporary
  variables?
\end{Ext}

\begin{Solution}
<<paperAreas>>=
usp <- things[["uspaper"]]
usp <- as.numeric(usp[-3])
usp <- 25.4 * as.numeric(usp)

eup <- things[["eupaper"]]
eup <- as.numeric(eup[-3])

prod(usp)
prod(eup)

## one line versions
prod(25.4 * as.numeric(things[["uspaper"]][-3]))
prod(as.numeric(things[["eupaper"]][-3]))
@
\end{Solution}


\section{Environments}
\label{sec:env}

The \Rclass{environment} type is a data structure that maps keys to
values.  In other programming languages these structures may be called
dictionaries, hash tables, or associative arrays.  The keys of \R's
\Rclass{environment}s must be strings, but the values can be arbitrary
\R{} objects.  The items in an \Rclass{environment} are not ordered
(unlike a named list).

Here is what basic \Rclass{environment} assignment and extraction
looks like:

<<envEx>>=
env <- new.env(parent = emptyenv())
## we haven't talked about assignment, but similar
## forms also work for lists (and with "[" for vectors).
env[["a"]] <- 1:3
env$b <- "hello"

env[["b"]]

env$a

mget(c("b", "a", "b"), env)

## list all keys
ls(env)
@

The \Rclass{environment} data type behaves differently than (almost)
all other data types in \R.  Other data types in \R{} have pass-by-value
semantics, which means that when you pass an object to a function or
assign it to a new variable name you make a \textit{copy} of the
original object.  \Rclass{environment}s have pass-by-reference
semantics, which means that \textit{no copy} is made when you pass an
\Rclass{environment} to a function or assign it to a new variable
name.  Here's an example to explore:

<<passByValVsRef>>=
## create an environment
env1 <- new.env(parent = emptyenv())
env1[["name"]] <- "alice"
env1[["count"]] <- 100

## create a similar list
lst1 <- list(name = "bob", count = 100)

## this just creates a new reference,
## NOT a copy
env2 <- env1

## this effectively copies the list
lst2 <- lst1

## now modify original environment and list
env1[["count"]] <- 200
lst1[["count"]] <- 200

## env2 points to same data as env1
env2[["count"]]

## but lst2 is a copy and was not changed
lst2[["count"]]
@


\section{Functions}

Defining your own functions is an essential part of creating efficient
and reproducible analyses as it allows you to organize a sequence of
computations into a unit that can be applied to any set of appropriate
inputs.

Here's a basic function definition:
<<basicFunctionDef>>=
say <- function(name, greeting = "hello")
{
    paste(greeting, name)
}

## these two calls use positional argument matching
say("world")
say("world", "goodbye")
## this call matches arguments by name, order
## doesn't matter for this case
say(greeting = "g'day", name = "Seattle")
@

The \textit{name} of this function is \Rfunction{say\_hello}.  It has
one \textit{formal argument}: \code{name}.  The \textit{body} of the
function is between the curly braces.  The return value of a function
in \R{} is the value of the last evaluated expression in the body.
Arguments to a function can specify default values, as is the case with
\code{greeting} above.  The default value is used if a value is not
provided when the function is called.

When calling functions in \R, you can provide arguments in the same
order as in the definition of the function, or you can name the
arguments as shown in the last call to \Rfunction{say} above.  Naming
arguments is a good practice because it makes code more
self-explanatory and robust (a change in the function's argument order
won't impact your call, for example).

\begin{Ext}
  Write a function that separates the data in the \Robject{Indometh}
  data.frame by subject.  Your function should take a single argument
  and return a list of data.frames such that each data.frame has the
  data for one of the subjects.  The returned list should have names
  Subject1, Subject2, \dots, Subject6 when given the
  \Robject{Indometh} data.frame as input.  Also, since the Subject
  column is now redundant, remove it from the subject-specific
  data.frames returned by your function.
\end{Ext}

\begin{Solution}
<<indomethFuncExample>>=
splitBySubject <- function(df)
{
    list(Subject1 = df[df$Subject == "1", -1],
         Subject2 = df[df$Subject == "2", -1],
         Subject3 = df[df$Subject == "3", -1],
         Subject4 = df[df$Subject == "4", -1],
         Subject5 = df[df$Subject == "5", -1],
         Subject6 = df[df$Subject == "6", -1])
}
@

We will explore some ways of making this more elegant in class.
\end{Solution}



\section{Getting Help in R}

You've already learned how to get help on a particular function in \R{}
using \code{help(funcName)}.  Here we'll discuss some other aspects of
\R's help system.

\subsection{HTML Help System}

In addition to ``online'' help accessed via \Rfunction{help} or
\Rfunction{?}, \R{} provides an HTML-based help system that you can
access locally using your web browser.  To start the help system
enter:
<<startHelp, eval=FALSE>>=
help.start()
@

There is a link ``Search Engine \& Keywords'' on the start page of
\Rfunction{help.start} that allows you to query the help system for a
topic of interest.  You can also search for help
using \Rfunction{help.search} and \Rfunction{RSiteSearch}, the latter
will search \R{} mailing lists in addition to documentation.  Finally,
\Rfunction{apropos} is useful for finding functions that are in the
current search path.

\begin{Ext}
  Find the function for performing a Mann-Whitney test.
\end{Ext}

\begin{Solution}
Executing \code{help.search("mann-whitney")} should lead you to
\Rfunction{wilcox.test}.
\end{Solution}

\begin{Ext}
  Find all the functions on your search path that have a name
  consisting of a single character.
\end{Ext}
\begin{Solution}
  See the example section of the manual page for \Rfunction{apropos}.
<<aproposExample>>=
apropos("^.$")
@
\end{Solution}


\subsection{Vignettes}

Many \R{} packages come with a \textit{vignette}, a short document
providing a detailed example of how to make use of the package's
functionality.  Vignettes contain executable \R{} code that allow you to
step through the examples as you read the document.  You can use the
\Rfunction{browseVignettes} function to explore the vignettes
available on your system.


\section{Exploring \R{} objects}

Every object in \R{} has an associated class which you can determine
using the \Rfunction{class} function.  This is often a good way to
begin exploring an unfamiliar object.  Other functions useful for
exploring are \Rfunction{length}, \Rfunction{dim},
\Rfunction{summary}, and \Rfunction{str}.

\begin{Ext}
  Execute the following call and then determine what type of object is
  stored in \Robject{pkgs}.
<<installedPackages>>=
pkgs <- installed.packages()
@
\end{Ext}

\begin{Solution}
<<whatIsIt>>=
class(pkgs)
@
\end{Solution}


\begin{Ext}
  What do the \Rfunction{length} and \Rfunction{dim} functions return
  for \Robject{pkgs}?  Can you reconcile the answers given by these
  two functions?
\end{Ext}

\begin{Solution}
<<lengthAndDimOfMatrix>>=
## matrices in R are stored as a vector
## with a dim attribute.  Data is stored
## in column-major order.
dp <- dim(pkgs)
length(pkgs)
dp[1] * dp[2]

@
\end{Solution}


\section{Session information}

<<sessionInfo, results=tex, echo=FALSE>>=
toLatex(sessionInfo())
@

\end{document}
