%\VignetteIndexEntry{Slides: Introduction to R}
%\VignetteDepends{}
%\VignetteIndexEntry{}
%\VignettePackage{SeattleIntro2010}

\documentclass{beamer}

\usepackage{BioconductorSlides}
\SweaveOpts{keep.source=TRUE}

\title{Introduction to R}
\author{Nishant Gopalakrishnan, Martin Morgan}
\institute{Fred Hutchinson Cancer Research Center}
\date{9-10 December, 2010}
\begin{document}
<<setup, echo=FALSE>>=
options(width = 40)
@

\frame{\titlepage}
\section[Outline]{}
\frame{\tableofcontents}
%---------------------------------------------------
\section{Getting Started}
 %---------------------------------------------------
\begin{frame}[fragile]{Getting help in R}
\begin{itemize}
\item \Rfunction{help} and \Rfunction{?}: \verb+help("data.frame")+ or ? data.frame
\item \Rfunction{help.search("slice")}, \Rfunction{apropos("mean")}
\item \Rfunction{browseVignettes("Biobase")}
\item \Rfunction{RSiteSearch} (requires internet connection)
\item R/Bioconductor mailing lists (\Rfunction{sessionInfo()})
\end{itemize}
\end{frame}
%---------------------------------------------------
\begin{frame}[fragile]{Data structures in R}
R has a rich set of \textit{self-describing} data structures.
\begin{itemize}
\item \Robject{vector} - array of the same type
\item \Robject{factor} - categorical
\item \Robject{list} - can contain objects of different types
\item \Robject{data.frame} - table-like
\item \Robject{matrix}
\item \Robject{environment} - hash table
\item \Robject{class} - arbitrary record type
\item \Robject{function}
\end{itemize}
\end{frame}

%---------------------------------------------------
\section{Atomic Data structures}
%---------------------------------------------------
\subsection{Creating vectors}
\begin{frame}[fragile]{Creating vectors}
There are two symbols that can be used for assignment: \verb+<-+ and
\verb+=+.
{\small
<<vectors, print=TRUE>>=
v <- 123
s <- "a string"
t <- TRUE
letters            # 'letters' is a built-in variable
length(letters)    # 'length' is a function
@
}
\end{frame}
%--------------------------------------------------
\begin{frame}[fragile]{Functions for Creating vectors}
\begin{itemize}
\item \Rfunction{c} - concatenate
\item \Rfunction{:} - integer sequence, \Rfunction{seq} - general sequence
\item \Rfunction{rep} - repetitive patterns
\item \Rfunction{vector} - vector of given length with default value
\end{itemize}
<<vectorsRepAndSeq>>=
seq(1, 3) 
1:3
rep(1:2, 3)
vector(mode="character", length=5)
@
\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Naming vectors}
The elements of a vector can be named
\begin{itemize}
\item at creation time
\item using \Rfunction{names}, \Rfunction{dimnames},
    \Rfunction{rownames}, \Rfunction{colnames}
\end{itemize}
<<names1>>=
x <- c(a=0, b=2)
x
names(x) <- c("Australia", "Brazil")
x
@
\end{frame}
%--------------------------------------------------
\subsection{Subsetting vectors}
%--------------------------------------------------
\begin{frame}[fragile]{Subsetting}
\begin{itemize}
\item One of the most powerful features of R is its ability to
      manipulate subsets of vectors and arrays.

\item Subsetting is indicated by \verb+[+, \verb+]+. 

\item Note that \verb+[+ is actually a function (try
  \verb+get("[")+). \verb+x[2, 3]+ is equivalent
  to \verb+"["(x, 2, 3)+.
  Its behavior can be customized for particular
  classes of objects.
\item The number of indices supplied to \verb+[+ must be
  either the dimension of \verb+x+ or 1.
\end{itemize}

\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Subsetting with positive indices}
\begin{itemize}
\item A subscript consisting of a vector of positive integer values is
      taken to indicate a set of indices to be extracted.
<<posind>>=
x <- 1:10
x[2]
x[1:3]
@
\item A subscript which is larger than the length of the vector being
      subset produces an NA in the returned value.
<<posind2>>=
 x[9:11]
@
\end{itemize}

\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Subsetting with positive indices (continued)}
\begin{itemize}
\item Subscripts which are zero are ignored and produce no
      corresponding values in the result.
<<posind3>>=
x[0:1]
x[c(0, 0, 0)]
@
\item Subscripts which are \Robject{NA} produce an \Robject{NA} in the
      result.
<<posind4>>=
x[c(10, 2, NA)]
@
\end{itemize}
\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Assignments with positive indices}
\begin{itemize}
\item Subset expressions can appear on the left side of an
      assignment. In this case the given subset is assigned the values
      on the right (recycling the values if necessary).
<<posassign>>=
x[2] <- 200
x[8:10] <- 10
x
@

\item If a zero or \Robject{NA} occurs as a subscript in this
      situation, it is ignored.
\end{itemize}
\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Subsetting with negative indices}
\begin{itemize}
\item A subscript consisting of a vector of negative integer values is
      taken to indicate the indices which are not to be extracted.
<<negsub>>=
x[-(1:3)]
@

\item Subscripts which are zero are ignored and produce no
      corresponding values in the result.

\item \Robject{NA} subscripts are not allowed.

\item Positive and negative subscripts cannot be mixed.
\end{itemize}

\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Assignments with negative indices}
\begin{itemize}
\item Negative subscripts can appear on the left side of an
      assignment. In this case the given subset is assigned the values
      on the right (recycling the values if necessary).
<<negassignb>>=
x = 1:10
x[-(8:10)] = 10
x
@

\item Zero subscripts are ignored.

\item \Robject{NA} subscripts are not permitted.
\end{itemize}
\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Subsetting by Logical Predicates}
\begin{itemize}
\item Vector subsets can also be specified by a logical vector of
      \Robject{TRUE}s and \Robject{FALSE}s.
<<logicalsub>>=
x = 1:10
x > 5
x[x > 5]
@
\item \Robject{NA} values used as logical subscripts produce
      \Robject{NA} values in the output.
\item The subscript vector can be shorter than the  vector being
      subsetted. The subscripts are recycled in this case.
\item The subscript vector can be longer than the vector being
      subsetted. Values selected beyond the end of the vector produce
      \Robject{NA}s.
\end{itemize}

\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Subsetting by name}
\begin{itemize}
\item If a vector has named elements, it is possible to extract
      subsets by specifying the names of the desired elements.
<<namedsub>>=
x <- c(a=1, b=2, c=3)
x[c("c", "a", "foo")]

@
\item If several elements have the same name, only the first of them
      will be returned.
\item Specifying a non-existent name produces an \Robject{NA} in the
      result.
\end{itemize}
\end{frame}
   
  
%--------------------------------------------------
\begin{frame}[fragile]{Vectorized arithmetic}
\begin{itemize}
\item Most arithmetic operations in the R language are
      \textit{vectorized}. That means that the operation is applied
      element-wise.
<<vec1>>=
1:3 + 10:12
@
\item When one operand is shorter than the other, the short operand is
  recycled until it is the same length as the longer operand.
<<vec2>>=
 1 + 1:5
 paste(1:5, "A", sep="")
@
\item Many operations which need to have explicit loops in other
      languages do not need them with R. You should vectorize
      any functions you write.
\end{itemize}

\end{frame}

%--------------------------------------------------
\section{Factors}
%--------------------------------------------------

\begin{frame}[fragile]{Factors}
\begin{itemize}
\item A special type of vector with grouping information about its components
\item A vector with its components grouped with distinct levels
\item
<<factor>>=
col <- c("red", "green", "red", "yellow", "red")
factor(col)
@
\end{itemize}
\end{frame}
%--------------------------------------------------
\section{Matrices and arrarys}
\begin{frame}[fragile]{Matrices and $n$-Dimensional Arrays}
\begin{itemize}
\item Can be created using \Rfunction{matrix} and \Rfunction{array}.
\item Are represented as a vector with a dimension attribute.
\item left most index is fastest (like Fortran or Matlab) \_
\end{itemize}
\end{frame}
%--------------------------------------------------
\begin{frame}[fragile]{Matrix examples}
<<matrixEx>>=
x <- matrix(1:10, nrow=2)
dim(x)
x
as.vector(x)
@
\end{frame}
%--------------------------------------------------
\begin{frame}[fragile]{Naming dimensions of matrix}
<<names2>>=
x <- matrix(c(4, 8, 5, 6, 4, 2, 1, 5, 7), nrow=3)
dimnames(x) <- list(
  year = c("2005", "2006", "2007"), 
  "mode of transport" = c("plane", "bus", "boat"))
x
@ 
\end{frame}


%--------------------------------------------------
\begin{frame}[fragile]{Subsetting matrices}
\begin{itemize}
\item When subsetting a matrix, missing subscripts are treated as if
  all elements are named; so \texttt{x[1,]}  corresponds to the first
  row and \texttt{x[,3]} to the third column.

\item For arrays, the treatment is similar, for example \texttt{y[,1,]}.
\item These can also be used for assignment, \texttt{x[1,]=20}

\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Subsetting arrays}
\begin{itemize}
\item Rectangular subsets of arrays obey similar rules to those which
      apply to vectors.
\item One point to note is that arrays can also be treated as 
  vectors. This can be quite useful.
<<arraysub>>=
 x = matrix(1:9, ncol=3)
 x[ x > 6 ]
 x[row(x) > col(x)] = 0
 x

@
\end{itemize}
\end{frame}
%--------------------------------------------------
\section{Lists}
\begin{frame}[fragile]{Lists}
\begin{itemize}
\item A list is an ordered set of elements that can be arbitrary R objects
      (vectors, other lists, functions, $\ldots$). In contrast to atomic
      vectors, which are homogeneous, lists and environments can be heterogeneous.
<<listenv>>=
 lst = list(a=1:3, b = "ciao", c = sqrt)
 lst
 lst$c(81)
@
\end{itemize}
\end{frame}

\subsection{Subsetting a list}
%--------------------------------------------------
\begin{frame}[fragile]{Subsetting and lists}
\begin{itemize}
\item Lists are useful as containers for grouping related thing
      together (many R functions return lists as their values).
\item Because lists are a recursive structure it is useful to have two
      ways of extracting subsets.
\item The \verb+[ ]+ form of subsetting produces a sub-list of the
      list being subsetted.
\item The \verb+[[ ]]+ form of subsetting can be used to extract a
      single element from a list.
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Subsetting and lists}
\begin{itemize}
\item Lists are useful as containers for grouping related thing
      together (many R functions return lists as their values).
\item Because lists are a recursive structure it is useful to have two
      ways of extracting subsets.
\item The \verb+[ ]+ form of subsetting produces a sub-list of the
      list being subsetted.
\item The \verb+[[ ]]+ form of subsetting can be used to extract a
      single element from a list.
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Subsetting lists }
\begin{itemize}
\item Using the \verb+[ ]+ operator to extract a sublist.
<<>>=
 lst[1]
@
\item Using the \verb+[[ ]]+ operator to extract a list element.
<<>>=
 lst[[1]]
@

\item As with vectors, indexing using logical expressions and names
      is also possible.
\end{itemize}

\end{frame}


%--------------------------------------------------
\begin{frame}[fragile]{Subsetting by name}
\begin{itemize}
\item The dollar operator provides a short-hand way of accessing list
      elements by name. This operator is different from all other
      operators in R, it does not \textit{evaluate} its second operand (the
      string).
<<>>=
 lst$a
 lst[["a"]]
@
\item For \verb+$+ partial matching is used, for \verb+[[+ it is not % ]]
  by default, but can be turned on.
\end{itemize}

\end{frame}
 

%--------------------------------------------------
\section{Environments}
\begin{frame}[fragile]{Environments}
\begin{itemize}
\item One difference between lists and environments is that there is
      no concept of ordering in an environment. All objects are stored
      and retrieved by \textbf{name}.
<<env1>>=
e1 = new.env()
e1[["a"]] <- 1:3
assign("b", "ciao", e1)
ls(e1)
@
\item Names must match exactly (for lists, partial matching is used
  for the \verb+$+ operator).
\end{itemize}
\end{frame}
 

%--------------------------------------------------
\begin{frame}[fragile]{Accesssing elements in an environment}

\begin{itemize}
\item Access to elements in environments can be through,
      \Rfunction{get}, \Rfunction{assign}, \Rfunction{mget}.
<<>>=
 mget(c("a", "b"), e1)
@ 
\item You can also use the dollar operator and the \verb+[[ ]]+
      operator, with character arguments only. No partial matching is
      done.
<<>>=
 e1$a
 e1[["b"]]
@
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Assigning values to lists and environments}
\begin{itemize}
\item Items in lists and environments can be (re)placed in much the same
      way as items in vectors are replaced.
<<>>=
 lst[[1]] = list(2,3)
 lst[[1]]

 e1$b = 1:10
 e1$b
@
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\section{Data frames}
\begin{frame}[fragile]{Data frames}
\begin{itemize}

\item Data frames are a special R structure used to hold a set of
      spreadsheet like table. In a \Robject{data.frame}, the
      observations are the rows and the covariates are the columns.

\item Data frames can be treated like matrices and be indexed with two
      subscripts. The first subscript refers to the observation, the
      second to the variable.
\item Data frames are really lists, and list subsetting can also be
      used on them.
\end{itemize}

\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Create a data frame}

<<dataFrameEx>>=
df <- data.frame(type=rep(c("case", "control"), c(2, 3)), 
                 time=rexp(5))
df
df$time
@ 

\end{frame}

%--------------------------------------------------
\begin{frame}[fragile]{Update row names}

<<dataFrameEx2>>=
names(df)
rn <- paste("id", 1:5, sep="")
rownames(df) <- rn
df[1:2, ]
@ 

\end{frame}


%--------------------------------------------------
\section{Control flow}
\begin{frame}[fragile]{Control Flow}
R has a standard set of control flow functions: 

\begin{itemize}
\item Looping: \Rfunction{for}, \Rfunction{while} and \Rfunction{repeat}.
\item Conditional evaluation: \Rfunction{if}
      and \Rfunction{switch}.
\end{itemize}

\end{frame}


%--------------------------------------------------
\subsection{apply}
\begin{frame}[fragile]{apply family of functions}
\begin{itemize}
\item A natural programming construct in R is to \textit{apply} the
      same function to elements of a list, of a vector, rows of a
      matrix, or elements of an environment.
\item The members of this family of functions are different with
      regard to the data structures they work on and how the answers
      are dealt with.
\item Some examples, \Rfunction{apply}, \Rfunction{sapply},
      \Rfunction{lapply}, \Rfunction{mapply}, \Rfunction{eapply}.
\end{itemize}

\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{\Rfunction{apply}}
\begin{itemize}
\item \Rfunction{apply} applies a function over the margins of an array.
\item For example, \\
\verb+ > apply(x, 2, mean)+ \\
computes the column means of a matrix \Robject{x}, while \\
\verb+ > apply(x, 1, median)+ \\
 computes the row medians.
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{\Rfunction{apply}}
\Rfunction{apply} is usually not faster than a \verb+for+ loop. But
it is more elegant.
<<apply1>>=
a = matrix(runif(1e6), ncol=10)
## 'apply'
s1 = apply(a, 1, sum)

## 'for', pre-allocating for efficiency
s2 = numeric(nrow(a))
for(i in 1:nrow(a))
  s2[i] = sum(a[i,])

## purpose-built function (much faster!)
s3 = rowSums(a)
@ 

\end{frame}
 
%--------------------------------------------------
\section{Functions}
\begin{frame}[fragile]{Writing functions}
\begin{itemize}
\item Writing R functions provides a means of adding new functionality
      to the language.
\item Functions that a user writes have the same status as those which
      are provided with R.
\item Reading the functions provided with the R system is a good way
      to learn how to write functions.
\end{itemize}

\end{frame}

 
%--------------------------------------------------
\begin{frame}[fragile]{Functions}
\begin{itemize}
\item Here is a function that computes the square of its argument.
<<sqfun>>=

 square = function(x){ 
            x*x
          }
 square(10)
@

\item Because the function body is vectorized, so is this new
      function.
<<sf2>>=
 square(1:4)
@
\end{itemize}
\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Composition of functions}
\begin{itemize}
\item Once a function is defined, it is possible to call it from other
      functions.
<<callsumsq>>=
 sumsq = function(x) sum(square(x))
 sumsq(1:10)
@
\end{itemize}

\end{frame}
 
%--------------------------------------------------
\begin{frame}[fragile]{Returning values}
\begin{itemize}

\item Any single R object can be returned as the value of a function;
  including a function.

\item If you want to return more than one object, you should put them
  in a list (usually with names), or an S4 object (discussed later),
  and return that.

\item The value returned by a function is either the value of the last
  statement executed, or the value of an explicit call to
  \Rfunction{return}.

\item \Rfunction{return} takes a single argument, and can be called
  from any where in a function.

\end{itemize}

\end{frame}
 
%---------------------------------------------------
\section{Visualizing data}   

\begin{frame}[fragile]{Visualizing data in R}
Basic plots
\begin{itemize} 
\item plot: x-y plotting
\item boxplot: box-whisker plot
\item hist: histogram
\item barplot: bar plot
\end{itemize}
\end{frame}
%---------------------------------------------------

\begin{frame}[fragile]{Basic scatter plot}
<<codeblock,eval=FALSE>>=
df <- data.frame("y" = 1:10, "x" = rnorm(10))
plot(df$x, df$y, col = "red")
@
\end{frame}

%%---------------------------------------------------
\begin{frame}[fragile]{Trellis graphics}
Lattice package
\begin{itemize} 
\item xyplot: scatter plot
\item bwplot: box-whisker plot
\item histogram: histogram
\item densityplot: kernel density plot
\end{itemize}
\end{frame}
%%---------------------------------------------------
\begin{frame}[fragile]{Lattice plots}
<<codeblock, eval = FALSE>>=
xyplot( y ~ x | c, data , groups = g)
@
\begin{itemize} 
\item lattice function
\item formula
    \begin{itemize}
    \item primary variables
    \item conditioning variable
    \end{itemize}
\item grouping variable
\item data
\end{itemize}
\end{frame}

%%---------------------------------------------------
\begin{frame}[fragile]{Reading/writing data from/to files}
\begin{itemize}
\item \Rfunction{read.delim("file")}, \Rfunction{read.table("file")}
\item \Rfunction{write.table}, \Rfunction{write}
\item \Rfunction{load}, \Rfunction{save}
\end{itemize}
\end{frame}
%---------------------------------------------------

\begin{frame}[fragile]{Packages}
\begin{itemize}
\item In R the primary mechanism for distributing software is via
  \textit{packages}.
\item The most reliable way to install Bioconductor packages (and
      their dependencies) is to use \Rfunction{biocLite}.
<<eval=FALSE>>=
 source("http://bioconductor.org/biocLite.R")
 biocLite("Biobase")
@ 
\item During an R session, use \Rfunction{library} to load a package
  in order to obtain access to its functionality.
<<eval=FALSE>>=
 library(Biobase)
@ 
\end{itemize}
\end{frame}

%%---------------------------------------------------
\begin{frame}[fragile]{Selected references}
\begin{itemize}
\item \textit{Software for Data Analysis: Programming with R} by
  J. Chambers.
\item \textit{R Programming for Bioinformatics} by R. Gentleman.
\item \textit{Lattice: Multivariate Data Visualization with R} by
  D. Sarkar.
\item \textit{Introductory Statistics with R} by P. Dalgaard.
\item \textit{Modern Applied Statistics}, \textit{S Programming} by
   W. N. Venables and B. D. Ripley.
\end{itemize}
Course resource
\begin{itemize}
\item \textit{Bioconductor Case Studies} by F. Hahne, W. Huber,
  R. Gentleman, and S. Falcon.
\end{itemize}
\end{frame}
\end{document}

