%\VignetteDepends{lattice, IRanges}
%\VignetteIndexEntry{Introduction to R}
%\VignettePackage{HTSandGeneCentricLabs}

\documentclass{beamer}
\usepackage{Bioconductor}
\SweaveOpts{keep.source=TRUE}

\title{Introduction to R}
\author{Chao-Jen Wong}
\institute[FHCRC]{Fred Hutchinson Cancer Research Center}
\date{29 July, 2010}

\begin{document}

<<setup, echo=FALSE>>=
options(width = 40)
@ 

\frame{\titlepage}

\section[Outline]{}
\frame{\tableofcontents}

\section{Introduction}

\begin{frame}[fragile]{Packages}
\textsf{R} distributes software via \textit{packages}. 
    \begin{itemize}
      \item \textit{CRAN} -- primarily for statistics research and data
        analysis. 
      \item \textit{Bioconductor} -- focus on analysis of high-throughput
        biological data. 
    \end{itemize}

   \begin{block}{Starting R}
     \begin{itemize}
        \item Finding packages
        \item Installing packages
        \item Attaching packages.
<<eval=FALSE>>=
library(HTSandGeneCentricLabs)
@           
     \end{itemize}
   \end{block}

\end{frame}

\begin{frame}[fragile]{Installing Packages}

  \begin{block}{Install Bioconductor packages (and their dependencies)}
<<biocLite, eval=FALSE>>=
source("http://bioconductor.org/biocLite.R")
biocLite()
@
  \end{block}

  \begin{block}{Install from source archive}
<<flowTrack, eval=FALSE>>=
pkg <- "myDir/HTSandGeneCentricLabs_1.0.0.tar.gz"
install.packages(pkg, repos=NULL, type="source")
@ 
  \end{block}
\end{frame}

\begin{frame}[fragile]{Getting Help in R}
  \begin{itemize}
    \item \Rfunction{help.start} and HTML help button in the Windows GUI
      
    \item \Rfunction{help} and \Rfunction{?}: \Rfunction{help('data.frame')}
      
    \item \Rfunction{help.search}, \Rfunction{apropos}
    \item \Rfunction{browseVignettes} - vignettes and corresponding R scripts
<<get vignettes, eval=FALSE>>=
browseVignettes("HTSandGeneCentricLabs")
@ 

    \item R Mailing lists
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{R Session}
  
<<results=hide>>=
library(IRanges)
## what is on the search path?
search() 
ls(2)
## package description of IRanges
packageDescription("IRanges")
@ 

<<results=hide>>=
## What functionalities does IRanges provide?
ls("package:IRanges")
#help(package="IRanges")
sessionInfo()
@ 
  
\end{frame}

\section{Atomic Vectors}
\begin{frame}[fragile]{Atomic Vectors}
Vector: one-dimensional array of items of the same type.
<<vector>>=
# numeric
L <- c(1.2, 4.3, 2.3, 4)
W <- c(13.8, 22.4, 18, 18.9) 
# most of functions are vectorized
length(L)
area <- L * W 
area
@ 
Other basic data types:
<<basic data types>>=
s <- "a string" # character
t <- TRUE # logical
i <- 1L # integer
i <- 1+1i # complex

@   
\end{frame}

\begin{frame}[fragile]{Functions for Creating Vectors}
  \begin{block}{Functions}
    \begin{itemize}
      \item \Rfunction{c} - concatenate
      \item \Rfunction{:} - integer sequences
      \item \Rfunction{rep} - repetitive patterns
    \end{itemize}
<<functions>>=
1:10
rep(1:2, 3)
@ 
  \end{block}
  
  \begin{block}{Exercise}
    \begin{enumerate} 
      \item Read the help page for \Rfunction{seq}
      \item Use \Rfunction{seq} to generate a sequence of even integers
        between one to ten.
    \end{enumerate}
  \end{block}
  
\end{frame}

\begin{frame}[fragile]{Subsetting Vectors}
  
  \begin{block}{Naming}
<<naming>>=
## name the elements of a vector
v <- c(a=1.1, b=2, c=100, d=50, e=60)
v
@ 
  \end{block}

  \begin{block}{Subsetting with positive indices}
<<>>=
v[c(1,3,4)]
@
  \end{block}
  \begin{block}{Subsetting with negative indices}
<<>>=
v[-c(1:3)] # exclude elements
@ 
  \end{block}
\end{frame}

\begin{frame}[fragile]{Subsetting Vectors}
  \begin{block}{By Logical predicates}
    Vector subsets can be specified by logical \Robject{TRUE}s and
    \Robject{FALSE}s. 
<<>>=
x <- 1:10
x > 5
x[x > 5]
@     
  \end{block}
  \begin{block}{\Robject{NA} as logical subscripts}
<<>>=
x[8:12]
@ 
  \end{block}
\end{frame}

\section{Matrix and data.frame}
\begin{frame}[fragile]{Matrix}
\Robject{matrix} - two-dimensional vector, all elements share a common type.

<<matrix>>=
x <- matrix(1:25, ncol=5, dimnames=list(letters[1:5], 
                            LETTERS[1:5]))
x
x[, 2]            
@ 
\end{frame}


\begin{frame}[fragile]{Matrix}
  \begin{block}{Exercise}
    \begin{enumerate}
      \item Remove the second row and the fourth column from \Robject{x}
      \item Subset \Robject{x} to keep the 'D' column.
    \end{enumerate}
  \end{block}
\end{frame}

\begin{frame}[fragile]{data.frame}
  \begin{itemize}
    \item A special \texttt{R} structure.
    \item Analogous to a table where each row represents a sample
      and each column an attribute of a sample. 
  \end{itemize}
\end{frame}
\begin{frame}[fragile]{data.frame}
<<data.frame>>=
df <- data.frame(type=c("case", "case", 
                "control", "control"), time=rexp(4))
df
df$time
names(df)

@ 
\end{frame}

\section{Lists and Environments}
\begin{frame}[fragile]{Lists}
\textit{Recursive} data structure -- a list can contain other lists and other
types of data structures. 

  
<<list>>=
lst <- list(a=1:4, b=c("X", "Y"), 
            uspaper=list(length=11, width=8.5))
lst
@   
\end{frame}

\begin{frame}[fragile]{Subsetting Lists}
  \begin{itemize}
    \item \Rfunction{[[} -- extracting a single element from a list
<<subset 1>>=
lst[[1]]
@ 
    \item \Rfunction{[} -- extracting a sub-list of the list
<<subset 2>>=
lst[1]
@       
    \item \Rfunction{\$} -- accessing list elements by name.
<<subset 3>>=
lst[["b"]]
@       
  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Environments}
Implementation of a hash table -- names are used to compute hash index and
hash index is used to retrieve the value.
<<environment>>=
el <- new.env()
el$a = 1:3
assign("b", "ciao", el)
ls(el)
el[["a"]]
el$b
@ 

\end{frame}

\section{Functions}
\begin{frame}[fragile]{Functions}
  \begin{block}{Creating a function}
<<hello world>>=
say <- function(name, greeting="hello") 
{
  paste(greeting, name)
}
say("world")
@ 
  \end{block}
  \begin{block}{Function code can be viewed}
<<view function, results=hide>>=
colSums
@ 
  \end{block}

\end{frame}

\begin{frame}[fragile]{Functions}{Return values}
Want to return more than one value? - make a list
<<circle>>=
circle <- function(radius) {
  area <- pi * radius^2
  circum <- 2 * pi * radius
  return(list(area=area, cm=circum))
}
circ <- circle(2)
circ
@   

\end{frame}

\begin{frame}[fragile]{Exploring R object}
  \begin{block}{\Rclass{factor} - category}
<<factor>>=
fac <- c(rep("normal",2), rep("tumor", 3), "unknown")
f <- factor(fac)
class(f)
levels(f)
str(f)
@ 
  \end{block}
  \begin{block}{Classes - arbitrary record type}
<<IRanges classes, eval=FALSE>>=
class ? IRanges
@     
  \end{block}
\end{frame}

\section{Basic Lattice}
\begin{frame}[fragile]{Basics}
  \begin{itemize}
    \item Provide  high-level functions for visualization of
      multivariate data.
    \item Implements the Trellis graphics system - multiple panels.
  \end{itemize}
<<lattice>>=
library(lattice)
@ 
  \begin{table}
    \centering
    \begin{tabular}{|ll|}
      \hline
      Function & Display \\ \hline
      \Rfunction{xyplot()} & Scatter Plot \\
      \Rfunction{dotplot()} & Dot Plot \\
      \Rfunction{bwplot()} & Box-and-Whisker Plots \\
      \Rfunction{densityplot()} & Kernel Density Plot \\
      \Rfunction{histogram()} & Histogram \\
      \Rfunction{contourplot()} & Contour Plot of Surface \\
      \Rfunction{cloud()} & 3-D Scatter Plot \\
      
      \hline
    \end{tabular}
    \caption{High-level functions in \Rpackage{lattice}.} 
  \end{table}
\end{frame}

\begin{frame}[fragile]{Basic Ideas}
  \begin{block}{An example}
<<quakes, eval=FALSE>>=
## quakes: locations of earthquakes off Fiji
Depth <- equal.count(quakes$depth, number=8, overlap=.1)
xyplot(lat ~ long | Depth, data = quakes)
@  
  \end{block}
\end{frame}

\begin{frame}[fragile]{Basic Ideas}

<<eval=FALSE>>=
xyplot(y ~ x | c, data, groups=g)
@   
  \begin{itemize}
    \item formula: \verb+y ~ x | c+
    \item primary variables: \verb+x+ and \verb+y+
    \item conditional variable: \verb+c+ -- a \Robject{factor} object,
      separate data into different panels
    \item group variable: \verb+g+, separate data into subgroups for
      superposition
    \item data: \verb+data+ -- a \Robject{data.frame} object
  \end{itemize}

\end{frame}

\begin{frame}[fragile]{Exercise}
<<>>=
data(Indometh)
df <- Indometh
head(df)
class(df)
@   


\end{frame}
%\begin{frame}[fragile]{Basics}
%\begin{figure}
%  \centering
%<<quakes, fig=TRUE, include=TRUE>>=
%## quakes: locations of earthquakes off Fiji
%Depth <- equal.count(quakes$depth, number=8, overlap=.1)
%xyplot(lat ~ long | Depth, data = quakes)
%@     
%  \end{figure}
%\end{frame}


%% reference
\begin{frame}{Selected Reference}
  \begin{itemize}
    \item \emph{Software for Data Analysis: Programming with R} by John
      Chambers. 
    \item \emph{R Programming for Bioinformatics} by Robert Gentleman.
    \item \emph{Multivariate Data Visualization with R} by Deepayan Sarker.
  \end{itemize}
\end{frame}


\end{document}
