\documentclass{beamer}
%\documentclass[handout]{beamer} aurait supprimé les ``overlays''
\newcommand{\mathem}[1]{$\boldsymbol{#1}$}
\newcommand{\key}[1]{{\normalfont\texttt{\uppercase{#1}}}}

\usepackage{fancyvrb}
\usepackage{amsmath,amssymb}
\definecolor{midnightblue}{rgb}{0.098,0.098,0.439}

\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl,formatcom={\color{violet}}}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{,formatcom={\color{midnightblue}}}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl,formatcom={\color{violet}}}
\newenvironment{Schunk}{}{}
\DefineVerbatimEnvironment{Code}{Verbatim}{,formatcom={\color{violet}}}
\DefineVerbatimEnvironment{CodeInput}{Verbatim}{fontshape=sl,formatcom={\color{violet}}}
\DefineVerbatimEnvironment{CodeOutput}{Verbatim}{,formatcom={\color{midnightblue}}}
\newenvironment{CodeChunk}{}{}

\newcommand{\commande}[1]{\texttt{#1}}

\newcommand{\vide}[1]{}
\newtheorem{proposition}{Proposition}
\newcommand{\prob}{\text{\fontfamily{cmss}\fontseries{sbc}\fontshape{n}\selectfont P}}
\newcommand{\Prob}{\text{\fontfamily{cmss}\fontseries{sbc}\fontshape{n}\selectfont P}}
%\newcommand{\transp}{^{\text{\fontfamily{cmss}\fontseries{sbc}\fontshape{n}\selectfont T}}}
\newcommand{\transp}{^{\text{\fontfamily{cmss}\fontseries{m}\fontshape{n}\selectfont T}}}
\newcommand{\Log}{\rm Log}
\newcommand{\Argmax}{\rm Argmax}
\newcommand{\Var}{\mathrm{Var}}
\newcommand{\var}{\mathrm{var}}
\newcommand{\Cov}{\mathrm{Cov}}
\newcommand{\cov}{\mathrm{cov}}
\def\ind {\mbox {\rm 1\!\!\,l}}%fonction indicatrice

% \usepackage{pdfanim}
% \input{pdfanim-patch}
% \PDFAnimLoad[loop,remember,startframe=1,scaletype=A,height=100pt,width=150pt]{cloud}{balls}{10}

\usetheme{Warsaw}% le thème choisi pour ma présentation
\useoutertheme[hooks]{tree}
%\usecolortheme{seahorse}



\DeclareGraphicsRule{.pdftex}{pdf}{.pdftex}{}



\usepackage[french]{babel}
%\usepackage[latin1]{inputenc}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{graphicx}%pour les includegraphics
\usepackage{array}% pour des tableaux particuliers. Nécessaire pour les révéler colonne par colonne
\usepackage{amsthm}
\usepackage{color}
%\usepackage{hyperref}
\usepackage{xspace} % rajouté le 25/05/2009
% On définit le symbole R
\newcommand{\R}{{\fontfamily{cmss}\fontseries{sbc}\fontshape{n}\selectfont R}\xspace}


\newtheorem{thm}{Théorème}
\newtheorem{result}{Résultat}
\newtheorem{boite}{}
\newtheorem{lemme}{Lemme}
\usepackage{bm,txfonts}
\newcommand{\gras}[1]{\ensuremath{\bm{\mathbf {#1}}}}

\newenvironment{cadre}[2]{%
\begin{center}%
$\text{ }$\\%
\fbox{$\text{ }$ $\text{ }$\parbox{0.9\textwidth}{%
$\text{ }$\\%
$\text{ }$\\%
#2%
$\text{ }$\\%
}$\text{ }$ $\text{ }$}
}{%
\end{center}%
}

\def\fleche{%
\begin{center}%
{\Huge \color{blue}$\Downarrow$\normalcolor}%
\end{center}}



\setbeamercovered{transparent}%l'autre option : invisible, cache totalement le texte pas encore découvert (ie, n'utilise pas le ``grisé'').

\colorlet{orange}{red!70!yellow}% mes petites couleurs que j'aime bien
\colorlet{mauve}{blue!70!red}
\colorlet{brouge}{red!70!blue}

\addtobeamertemplate{footline}{$\quad$\insertframenumber/\inserttotalframenumber\phantom{a}}
%pour ajouter un numéro de page en bas.
% une autre solution : \useoutertheme{shadow}


\title[Introductory course on the \R software]{Introductory course on the \R software}
%l'argument entre [] est une version courte du titre, qu'on met en bas des transparents.

\author[Lafaye de Micheaux, Pierre] % (optionnel, utiliser seulement s'il y a beaucoup d'auteurs)
{\textbf{P.~Lafaye de Micheaux}\inst{1}}


\institute[Départements et Universités] % (optionnel, mais nécessaire la plupart du temps)
{
  \inst{1}%
  	Mathematics and Statistics Departement\\
  	Université de Montréal\\
	CANADA
}

\date[2014]{New South Wales University\\
Sydney, Australia\\ June 3, 2014\\
\vspace{1ex}
\url{https://biostatisticien.eu/springeR/courseRw4.pdf}
}

%\AtBeginSection[] % pour mettre la table des matières 
%                 % au début de chaque section
%{ \begin{frame}<beamer> 
%\frametitle{Plan de la présentation} 
%\tableofcontents[currentsection] 
%\end{frame} }

 \pgfdeclareimage[height=96mm,width=128mm]{nombidon}{BatimentGIN}
  \setbeamertemplate{background}{\pgfuseimage{nombidon}}

% \logo{\includegraphics[width=1.5cm]{Rlogo.jpg}}% je définis le logo qui sera mis sur tous les transparents

\setbeamertemplate{background}{transparent}

\usepackage{ragged2e}
\justifying



\usepackage{algpseudocode,algorithm}


\RequirePackage{xcolor} 
\definecolor{beaubleu}{rgb}{0.26,0.31,0.61}
\definecolor{beauvert}{rgb}{0.27,0.52,0.42}


\usepackage{upquote}

\begin{document}


\begin{frame}
\titlepage


\vfill
\end{frame}

%\begin{frame}
%\tableofcontents[pausesections]
%\vspace*{\fill}
%\end{frame}



\section{Goals}

\begin{frame}
\frametitle{Goals of today lecture}

Describing the instructions for
\begin{itemize}
\item elementary data manipulation;
%\item control structures;
\item extraction tool (direct and by logical mask);
\item dealing with character strings.
\end{itemize}

\end{frame}

\section{Operations on vectors, matrices and lists}


\begin{frame}[fragile]
\frametitle{Vector arithmetic}

\R can operate on vectors\index{vectors} and matrices\index{matrices}:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ x <- c(1,2,4,6,3)}
>\textcolor{beaubleu}{ y <- c(4,7,8,1,1)}
>\textcolor{beaubleu}{ x + y}
\textit{\textcolor{beauvert}{[1]  5  9 12  7  4}}
\end{Verbatim}

\noindent Returns the vector of sums $(x_1+y_1,\ldots,x_n+y_n)$.\\
$ $\\
This is one of the \textbf{main strengths} of \R. It is called \textbf{vectorization}.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ M <- matrix(1:9,nrow=3)}
>\textcolor{beaubleu}{ exp(M)}
\textit{\textcolor{beauvert}{          [,1]      [,2]     [,3]}}
\textit{\textcolor{beauvert}{[1,]  2.718282  54.59815 1096.633}}
\textit{\textcolor{beauvert}{[2,]  7.389056 148.41316 2980.958}}
\textit{\textcolor{beauvert}{[3,] 20.085537 403.42879 8103.084}}
\end{Verbatim}
\end{frame}



\begin{frame}[fragile]
\frametitle{Vectorization is much quicker}
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ x <- rnorm(1000000)}
>\textcolor{beaubleu}{ system.time({z<-0;for(i in 1:1000000) z <- z + x[i]})}
\textit{\textcolor{beauvert}{   user  system elapsed }}
\textit{\textcolor{beauvert}{  1.143   0.009   1.154 }}
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 367.689}}
>\textcolor{beaubleu}{ system.time(z <- sum(x))}
\textit{\textcolor{beauvert}{   user  system elapsed }}
\textit{\textcolor{beauvert}{  0.002   0.000   0.003 }}
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 367.689}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Recycling}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{# Vector of length 15:}
>\textcolor{beaubleu}{ x <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)}
\textcolor{beaubleu}{# Vector of length 10:}
>\textcolor{beaubleu}{ y <- c(1,2,3,4,5,6,7,8,9,10)                }
\textcolor{beaubleu}{# Vector of length 15:}
>\textcolor{beaubleu}{ x + y                                         }
\textit{\textcolor{beauvert}{ [1]  2  4  6  8 10 12 14 16 18 20 12 14 16 18 20}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ matrix(1:4,ncol=3,nrow=3)}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    4    3}}
\textit{\textcolor{beauvert}{[2,]    2    1    4}}
\textit{\textcolor{beauvert}{[3,]    3    2    1}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Basic functions}

$\bullet$ \commande{length()}: returns the length of a vector.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ length(c(1,3,6,2,7,4,8,1,0))}
\textit{\textcolor{beauvert}{[1] 9}}
\end{Verbatim}

$\bullet$ \commande{sort()}: sorts the elements of a vector, in increasing or decreasing order.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ sort(c(1,3,6,2,7,4,8,1,0))}
\textit{\textcolor{beauvert}{[1] 0 1 1 2 3 4 6 7 8}}
>\textcolor{beaubleu}{ sort(c(1,3,6,2,7,4,8,1,0),decreasing=TRUE)}
\textit{\textcolor{beauvert}{[1] 8 7 6 4 3 2 1 1 0}}
\end{Verbatim}

$\bullet$ \commande{rev()}: rearranges the elements of a vector in reverse order.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ rev(c(1,3,6,2,7,4,8,1,0))}
\textit{\textcolor{beauvert}{[1] 0 1 8 4 7 2 6 3 1}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Basic functions}

$\bullet$ \commande{order()}, \commande{rank()} : the first function returns the vector of (increasing or decreasing) ranking indices\index{vectors!ranking indices} of the elements. The second function returns the vector of ranks\index{vectors!vector of ranks}\index{ranks} of the elements. In case of a tie\index{tie}, the ordering is always from left to right.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ vec <- c(1,3,6,2,7,4,8,1,0) ; names(vec) <- 1:9}
>\textcolor{beaubleu}{ vec}
\textit{\textcolor{beauvert}{1 2 3 4 5 6 7 8 9 }}
\textit{\textcolor{beauvert}{1 3 6 2 7 4 8 1 0 }}
>\textcolor{beaubleu}{ sort(vec)}
\textit{\textcolor{beauvert}{9 1 8 4 2 6 3 5 7 }}
\textit{\textcolor{beauvert}{0 1 1 2 3 4 6 7 8 }}
>\textcolor{beaubleu}{ order(vec)}
\textit{\textcolor{beauvert}{[1] 9 1 8 4 2 6 3 5 7}}
>\textcolor{beaubleu}{ rank(vec)}
\textit{\textcolor{beauvert}{  1   2   3   4   5   6   7   8   9 }}
\textit{\textcolor{beauvert}{2.5 5.0 7.0 4.0 8.0 6.0 9.0 2.5 1.0 }}
\end{Verbatim}


\end{frame}


\begin{frame}[fragile]
\frametitle{Operations on matrices and data.frames}

Perform the ``\textbf{Do it yourself}'' on page 89.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap5.pdf}\\
$ $\\
\textbf{Note:} You may have to first install the executable file \\
\url{http://biostatisticien.eu/springeR/Rtools29.exe}\\
and then to install and load from within \R the package \texttt{gdata}.
\end{frame}

\begin{frame}[fragile]
\frametitle{Merging columns of matrices or data.frames}

The generic function is \commande{cbind()}.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ cbind(1:4,5:8)}
\textit{\textcolor{beauvert}{     [,1] [,2]}}
\textit{\textcolor{beauvert}{[1,]    1    5}}
\textit{\textcolor{beauvert}{[2,]    2    6}}
\textit{\textcolor{beauvert}{[3,]    3    7}}
\textit{\textcolor{beauvert}{[4,]    4    8}}
\end{Verbatim}

\end{frame}

\begin{frame}[fragile]
\frametitle{Merging columns of matrices or data.frames}

Try to merge these two tables using \commande{cbind()}:
\begin{table}[h]
\tiny\centering
X1=\begin{tabular}{c|c|c}
Id & GENDER & Weight\\
\hline
1  &  M   & 75\\
2  &  F   & 68\\
3  &  F   & 48\\
4  &  M   & 72\\
\end{tabular} $\qquad\boldsymbol{\cup}\qquad$ X2=\begin{tabular}{c|c|c}
Id & GENDER & Height\\
\hline
1  &  M   & 182\\
2  &  F   & 165\\
3  &  F   & 160\\
4  &  M   & 178\\
\end{tabular}
\end{table}

What is the problem? \\
$ $\\
Now, try using the \commande{merge()} function.

\end{frame}

\begin{frame}[fragile]
\frametitle{Merging columns of matrices or data.frames}


\vspace*{-0.45cm}\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\tiny,fontseries=b]
>\textcolor{beaubleu}{ X }                                      >\textcolor{beaubleu}{ Y}
\textit{\textcolor{beauvert}{  GENDER Height Weight Income}}             \textit{\textcolor{beauvert}{  GENDER Height Weight Salary}}
\textit{\textcolor{beauvert}{1      F    165     50     80}}             \textit{\textcolor{beauvert}{4      F    165     55     70}}
\textit{\textcolor{beauvert}{2      M    182     65     90}}             \textit{\textcolor{beauvert}{5      M    182     65     90}}
\textit{\textcolor{beauvert}{3      M    178     67     60}}             \textit{\textcolor{beauvert}{6      M    178     67     40}}
\textit{\textcolor{beauvert}{4      F    160     55     50}}             \textit{\textcolor{beauvert}{7      F    160     85     40}}

>\textcolor{beaubleu}{ merge(X,Y,by=c("GENDER","Weight"))}
\textit{\textcolor{beauvert}{  GENDER Weight Height.x Income Height.y Salary}}
\textit{\textcolor{beauvert}{1      F     55      160     50      165     70}}
\textit{\textcolor{beauvert}{2      M     65      182     90      182     90}}
\textit{\textcolor{beauvert}{3      M     67      178     60      178     40}}

>\textcolor{beaubleu}{ merge(X,Y,by=c("GENDER","Weight"),all=TRUE)}
\textit{\textcolor{beauvert}{  GENDER Weight Height.x Income Height.y Salary}}
\textit{\textcolor{beauvert}{1      F     50      165     80       NA     NA}}
\textit{\textcolor{beauvert}{2      F     55      160     50      165     70}}
\textit{\textcolor{beauvert}{3      F     85       NA     NA      160     40}}
\textit{\textcolor{beauvert}{4      M     65      182     90      182     90}}
\textit{\textcolor{beauvert}{5      M     67      178     60      178     40}}
\end{Verbatim}

\end{frame}

\begin{frame}[fragile]
\frametitle{Merging lines of matrices or data.frames}

The generic function is \commande{rbind()}.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ rbind(1:4,5:8)}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3] [,4]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3    4}}
\textit{\textcolor{beauvert}{[2,]    5    6    7    8}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Merging lines of matrices or data.frames}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\tiny,fontseries=b]
>\textcolor{beaubleu}{ require(gtools)}
>\textcolor{beaubleu}{ df1 <- data.frame(A=1:5, B=LETTERS[1:5])   # The square}
\textcolor{beaubleu}{                                             # brackets [] to}
\textcolor{beaubleu}{                                             # extract}
>\textcolor{beaubleu}{ df2 <- data.frame(A=6:10, E=letters[1:5])  # elements will}
\textcolor{beaubleu}{                                             # be described}
\textcolor{beaubleu}{                                             # later.}
>\textcolor{beaubleu}{ smartbind(df1, df2)}
\textit{\textcolor{beauvert}{     A    B    E}}
\textit{\textcolor{beauvert}{1.1  1    A <NA>}}
\textit{\textcolor{beauvert}{1.2  2    B <NA>}}
\textit{\textcolor{beauvert}{1.3  3    C <NA>}}
\textit{\textcolor{beauvert}{1.4  4    D <NA>}}
\textit{\textcolor{beauvert}{1.5  5    E <NA>}}
\textit{\textcolor{beauvert}{2.1  6 <NA>    a}}
\textit{\textcolor{beauvert}{2.2  7 <NA>    b}}
\textit{\textcolor{beauvert}{2.3  8 <NA>    c}}
\textit{\textcolor{beauvert}{2.4  9 <NA>    d}}
\textit{\textcolor{beauvert}{2.5 10 <NA>    e}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{The function \texttt{apply()}}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ ( X <- matrix(c(1:4, 1, 6:8), nr = 2) )}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3] [,4]}}
\textit{\textcolor{beauvert}{[1,]    1    3    1    7}}
\textit{\textcolor{beauvert}{[2,]    2    4    6    8}}
>\textcolor{beaubleu}{ apply(X, MARGIN=1, FUN=mean)  }
\textit{\textcolor{beauvert}{[1] 3 5}}
>\textcolor{beaubleu}{ apply(X, MARGIN=2, FUN=sum)}
\textit{\textcolor{beauvert}{[1]  3  7  7 15}}
\end{Verbatim}

When the operation is summing or calculating the means of rows or columns, other possible functions are: \commande{rowSums()}, \commande{colSums()}, \commande{rowMeans()}, \commande{colMeans()}.\\
$ $\\
Perform the ``\textbf{Do it yourself}'' on page 93.


\end{frame}



\begin{frame}[fragile]
\frametitle{The function \texttt{transform()}}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ ( X <- data.frame(Weight=c(80,75,60,52),Height=c(180,}
+\textcolor{beaubleu}{            170,165,150),Cholesterol=c(44,12,23,34),}
+\textcolor{beaubleu}{          Gender=c("Male","Male","Female","Female")) )}
\textit{\textcolor{beauvert}{  Weight Height Cholesterol Gender}}
\textit{\textcolor{beauvert}{1     80   180          44   Male}}
\textit{\textcolor{beauvert}{2     75   170          12   Male}}
\textit{\textcolor{beauvert}{3     60   165          23 Female}}
\textit{\textcolor{beauvert}{4     52   150          34 Female}}
>\textcolor{beaubleu}{ ( X <- transform(X,Height=Height/100, }
>\textcolor{beaubleu}{           BMI=Weight/(Height/100)^2) )}
\textit{\textcolor{beauvert}{  Weight Height Cholesterol Gender      BMI}}
\textit{\textcolor{beauvert}{1     80   1.80          44   Male 24.69136}}
\textit{\textcolor{beauvert}{2     75   1.70          12   Male 25.95156}}
\textit{\textcolor{beauvert}{3     60   1.65          23 Female 22.03857}}
\textit{\textcolor{beauvert}{4     52   1.50          34 Female 23.11111}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Operations on lists: the function \commande{lapply()}}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
>\textcolor{beaubleu}{ x <- list(a = 1:10, beta = exp(-3:3), }
+\textcolor{beaubleu}{      logic = c(TRUE,FALSE,FALSE,TRUE))}
>\textcolor{beaubleu}{ lapply(x,mean) # Mean of each element of the list.}
\textit{\textcolor{beauvert}{$a}}
\textit{\textcolor{beauvert}{[1] 5.5}}
\textit{\textcolor{beauvert}{$beta}}
\textit{\textcolor{beauvert}{[1] 4.535125}}
\textit{\textcolor{beauvert}{$logic}}
\textit{\textcolor{beauvert}{[1] 0.5}}
\end{Verbatim}


\end{frame}


\begin{frame}[fragile]
\frametitle{Logical and relational operations}

Have a look at the Table 5.1 on page 98.

\end{frame}

\begin{frame}[fragile]
\frametitle{Operations on sets}

\begin{figure}[h]
\centering\includegraphics[width=3cm]{img/venn.png}
\end{figure}


\begin{table}[h]
\centering\tiny
\caption{Operations on sets.}\label{foncensembles}
\begin{tabular}{l|l|l}
Operation & \R Instruction & Output\\
\hline
\hline
Membership: $a\in A$ & \texttt{is.element(vec,A)} & \texttt{T F T} \\
Inclusion (subset): $A\subset B$ & \texttt{all(A \%in\% B)} &  \texttt{F}\\
Superset: $A\supset B$ & \texttt{all(B \%in\% A)} & \texttt{F}  \\
Intersection: $A\cap B$ & \texttt{intersect(A,B)} & \texttt{2 7}  \\
Union: $A\cup B$ & \texttt{union(A,B)} &  \texttt{4 6 2 7 1 3} \\
Complement: $A\backslash B$ & \texttt{setdiff(A,B)} & \texttt{4 6}  \\
Symmetric difference: $(A\cup B)\backslash (A\cap B)$ & \texttt{setdiff(union(A,B),intersect(A,B))} &  \texttt{4 6 1 3} \\
\end{tabular}
\end{table}

Create \verb#A#, \verb#B# and \verb#vec <- c(2,3,7)# and play with these functions!

\end{frame}

\begin{frame}[fragile]
\frametitle{Extracting from vectors}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
>\textcolor{beaubleu}{ vec <- c(2,4,6,8,3)}
>\textcolor{beaubleu}{ vec[2]}
\textit{\textcolor{beauvert}{[1] 4}}
>\textcolor{beaubleu}{ "["(vec,2)        # Note: "[" is indeed a function.}
\textit{\textcolor{beauvert}{[1] 4}}
>\textcolor{beaubleu}{ vec[-2]           # All elements except the second.}
\textit{\textcolor{beauvert}{[1] 2 6 8 3}}
>\textcolor{beaubleu}{ vec[2:5]}
\textit{\textcolor{beauvert}{[1] 4 6 8 3}}
>\textcolor{beaubleu}{ vec[-c(1,5)]}
\textit{\textcolor{beauvert}{[1] 4 6 8}}
>\textcolor{beaubleu}{ vec[c(T,F,F,T,T)] # Extraction by logical mask.}
\textit{\textcolor{beauvert}{[1] 2 8 3}}
>\textcolor{beaubleu}{ vec>4}
\textit{\textcolor{beauvert}{[1] FALSE FALSE  TRUE  TRUE FALSE}}
>\textcolor{beaubleu}{ vec[vec>4]        # Extraction by logical mask.}
\textit{\textcolor{beauvert}{[1] 6 8}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Extracting from vectors}

It is important to note here the syntactical simplicity of an instruction such as \verb#x[y>0]#, which extracts from \verb#x# all elements of index $i$ such that $y_i>0$.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ x <- 1:5}
>\textcolor{beaubleu}{ y <- c(-1,2,-3,4,-2)}
>\textcolor{beaubleu}{ x[y>0]}
\textit{\textcolor{beauvert}{[1] 2 4}}
\end{Verbatim}

You need to learn to use as often as possible such constructions, which are called \textbf{logical masks}\index{logical mask}. There are two advantages: the code is easy to read, and  execution is very fast.\\
$ $\\
Note: the functions \commande{which()}, \commande{which.min()} and  \commande{which.max()} are often very useful.



\end{frame}

\begin{frame}[fragile]
\frametitle{Replacement into vectors}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 0 0 0 2 0}}
>\textcolor{beaubleu}{ z[c(1,5)] <- 1}
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 1 0 0 2 1}}
>\textcolor{beaubleu}{ z[which.max(z)] <- 0 }
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 1 0 0 0 1}}
>\textcolor{beaubleu}{ z[z==0] <- 8  # The \mathem{z\sb{i}} such that}
\textcolor{beaubleu}{                # \mathem{z\sb{i}} is worth 0 are replaced with}
\textcolor{beaubleu}{                # 8.}
>\textcolor{beaubleu}{ z}
\textit{\textcolor{beauvert}{[1] 1 8 8 8 1}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Insertion into vectors}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ vecA <- c(1, 3, 6, 2, 7, 4, 8, 1, 0)}
>\textcolor{beaubleu}{ vecA}
\textit{\textcolor{beauvert}{[1] 1 3 6 2 7 4 8 1 0}}
>\textcolor{beaubleu}{ (vecB <- c(vecA, 4, 1))}
\textit{\textcolor{beauvert}{ [1] 1 3 6 2 7 4 8 1 0 4 1}}
>\textcolor{beaubleu}{ (vecC <- c(vecA[1:4], 8, 5, vecA[5:9]))}
\textit{\textcolor{beauvert}{ [1] 1 3 6 2 8 5 7 4 8 1 0}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ a <- c()}
>\textcolor{beaubleu}{ a <- c(a,2)}
>\textcolor{beaubleu}{ a <- c(a,7)}
>\textcolor{beaubleu}{ a}
\textit{\textcolor{beauvert}{[1] 2 7}}
\end{Verbatim}

Perform the ``\textbf{Do it yourself}'' on page 102.
\end{frame}

\begin{frame}[fragile]
\frametitle{Extraction from matrices}

Two methods are possible to extract elements from a matrix \verb#X#. Each method has its own syntax.
\begin{enumerate}
 \item \textit{Extracting by indices:} \verb#X[indr,indc]#, where \verb#indr# is the vector of indices of rows and  \verb#indc# is the vector of indices of columns to extract. Omitting \verb#indr# (respectively \verb#indc#) means that all rows are selected (respectively all columns). Note that \verb#indr# and \verb#indc# can be preceded by a minus sign (\verb#-#) to indicate elements not to extract.
\item \textit{Extracting by logical mask:} \verb#X[mask]#, where \verb#mask# is a matrix of logical values \verb#TRUE/FALSE# of the same size as \verb#X#, indicating which elements to extract.\\
\end{enumerate}


\end{frame}

\begin{frame}[fragile]
\frametitle{Extraction from matrices}

\vspace*{-0.2cm}\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ ( Mat <- matrix(1:12,nrow=4,ncol=3,byrow=TRUE) )}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3}}
\textit{\textcolor{beauvert}{[2,]    4    5    6}}
\textit{\textcolor{beauvert}{[3,]    7    8    9}}
\textit{\textcolor{beauvert}{[4,]   10   11   12}}
>\textcolor{beaubleu}{ Mat[2,3]        # Extracting the element at the}
\textcolor{beaubleu}{                  # intersection of row 2 and column 3.}
\textit{\textcolor{beauvert}{[1] 6}}
>\textcolor{beaubleu}{ Mat[,1]         # All rows, and only column 1.}
\textit{\textcolor{beauvert}{[1]  1  4  7 10}}
>\textcolor{beaubleu}{ Mat[c(1,4),]    # All columns, and rows 1 and 4.}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3}}
\textit{\textcolor{beauvert}{[2,]   10   11   12}}
>\textcolor{beaubleu}{ Mat[3,-c(1,3)]  # Row 3 and column 2.}
\textit{\textcolor{beauvert}{[1] 8}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Extraction from matrices (logical mask)}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ MatLogical <- matrix(c(TRUE,FALSE),nrow=4,ncol=3)}
>\textcolor{beaubleu}{ MatLogical      # Is of the same size as Mat.}
\textit{\textcolor{beauvert}{      [,1]  [,2]  [,3]}}
\textit{\textcolor{beauvert}{[1,]  TRUE  TRUE  TRUE}}
\textit{\textcolor{beauvert}{[2,] FALSE FALSE FALSE}}
\textit{\textcolor{beauvert}{[3,]  TRUE  TRUE  TRUE}}
\textit{\textcolor{beauvert}{[4,] FALSE FALSE FALSE}}
>\textcolor{beaubleu}{ Mat[MatLogical] # Make sure that you understand this}
\textcolor{beaubleu}{                  # instruction.}
\textit{\textcolor{beauvert}{[1] 1 7 2 8 3 9}}
\end{Verbatim}

%Perform the ``\textbf{Do it yourself}'' on page 104.


\end{frame}

\begin{frame}[fragile]
\frametitle{Extraction from matrices}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ m <- matrix(c(1,2,3,1,2,3,2,1,3),3,3)}
>\textcolor{beaubleu}{ m}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    1    2}}
\textit{\textcolor{beauvert}{[2,]    2    2    1}}
\textit{\textcolor{beauvert}{[3,]    3    3    3}}
>\textcolor{beaubleu}{ which(m == 1)        # m is seen as the concatenation}
\textcolor{beaubleu}{                       # of its columns.}
\textit{\textcolor{beauvert}{[1] 1 4 8}}
>\textcolor{beaubleu}{ which(m == 1,arr.ind=TRUE) #Outputs indices as couples.}
\textit{\textcolor{beauvert}{     row col}}
\textit{\textcolor{beauvert}{[1,]   1   1}}
\textit{\textcolor{beauvert}{[2,]   1   2}}
\textit{\textcolor{beauvert}{[3,]   2   3}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Insertion into matrices}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\tiny,fontseries=b]
>\textcolor{beaubleu}{ m}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    1    2}}
\textit{\textcolor{beauvert}{[2,]    2    2    1}}
\textit{\textcolor{beauvert}{[3,]    3    3    3}}
>\textcolor{beaubleu}{ m[m!=2] <- 0}
>\textcolor{beaubleu}{ m}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    0    0    2}}
\textit{\textcolor{beauvert}{[2,]    2    2    0}}
\textit{\textcolor{beauvert}{[3,]    0    0    0}}
>\textcolor{beaubleu}{ Mat <- Mat[-4,] ; Mat}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3}}
\textit{\textcolor{beauvert}{[2,]    4    5    6}}
\textit{\textcolor{beauvert}{[3,]    7    8    9}}
>\textcolor{beaubleu}{ m[Mat>7] <- Mat[Mat>7]}
>\textcolor{beaubleu}{ m}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    0    0    2}}
\textit{\textcolor{beauvert}{[2,]    2    2    0}}
\textit{\textcolor{beauvert}{[3,]    0    8    9}}
\end{Verbatim}

Perform the ``\textbf{Do it yourself}'' on page 105.


\end{frame}

\begin{frame}[fragile]
  \frametitle{Extracting from Lists}

\vspace*{-0.3cm}\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\tiny,fontseries=b]
>\textcolor{beaubleu}{ ( L <- list(12,c(34,67,8),Mat,1:15,list(10,11))  )}
\textit{\textcolor{beauvert}{[[1]]}}
\textit{\textcolor{beauvert}{[1] 12}}
\textit{\textcolor{beauvert}{[[2]]}}
\textit{\textcolor{beauvert}{[1] 34 67  8}}
\textit{\textcolor{beauvert}{[[3]]}}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3}}
\textit{\textcolor{beauvert}{[2,]    4    5    6}}
\textit{\textcolor{beauvert}{[3,]    7    8    9}}
\textit{\textcolor{beauvert}{[[4]]}}
\textit{\textcolor{beauvert}{ [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15}}
\textit{\textcolor{beauvert}{[[5]]}}
\textit{\textcolor{beauvert}{[[5]][[1]]}}
\textit{\textcolor{beauvert}{[1] 10}}
\textit{\textcolor{beauvert}{[[5]][[2]]}}
\textit{\textcolor{beauvert}{[1] 11}}
>\textcolor{beaubleu}{ L[2]}
\textit{\textcolor{beauvert}{[[1]]}}
\textit{\textcolor{beauvert}{[1] 34 67  8}}
>\textcolor{beaubleu}{ class(L[2])}
\textit{\textcolor{beauvert}{[1] "list"}}
>\textcolor{beaubleu}{ L[c(3,4)]}
\textit{\textcolor{beauvert}{[[1]]}}
\textit{\textcolor{beauvert}{     [,1] [,2] [,3]}}
\textit{\textcolor{beauvert}{[1,]    1    2    3}}
\textit{\textcolor{beauvert}{[2,]    4    5    6}}
\textit{\textcolor{beauvert}{[3,]    7    8    9}}
\textit{\textcolor{beauvert}{[[2]]}}
\textit{\textcolor{beauvert}{ [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Extracting from Lists}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ L[[2]]}
\textit{\textcolor{beauvert}{[1] 34 67  8}}
>\textcolor{beaubleu}{ "[["(L,2)}
\textit{\textcolor{beauvert}{[1] 34 67  8}}
>\textcolor{beaubleu}{ class(L[[2]])}
\textit{\textcolor{beauvert}{[1] "numeric"}}
>\textcolor{beaubleu}{ L[[5]][[2]]}
\textit{\textcolor{beauvert}{[1] 11}}
>\textcolor{beaubleu}{ L <- list(cars=c("FORD","PEUGEOT"),climate=}
+\textcolor{beaubleu}{                       c("Tropical","Temperate"))}
>\textcolor{beaubleu}{ L[["cars"]]}
\textit{\textcolor{beauvert}{[1] "FORD"    "PEUGEOT"}}
>\textcolor{beaubleu}{ L$cars}
\textit{\textcolor{beauvert}{[1] "FORD"    "PEUGEOT"}}
>\textcolor{beaubleu}{ L$climate}
\textit{\textcolor{beauvert}{[1] "Tropical"  "Temperate"}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Inserting into Lists}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ L$climate[2] <- "Continental"}
>\textcolor{beaubleu}{ L}
\textit{\textcolor{beauvert}{$cars}}
\textit{\textcolor{beauvert}{[1] "FORD"    "PEUGEOT"}}
\textit{\textcolor{beauvert}{$climate}}
\textit{\textcolor{beauvert}{[1] "Tropical"    "Continental"}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Manipulating character strings}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
>\textcolor{beaubleu}{ ( string <- c("one","two","three") )}
\textit{\textcolor{beauvert}{[1] "one"   "two"   "three"}}
>\textcolor{beaubleu}{ as.character(1:3)}
\textit{\textcolor{beauvert}{[1] "1" "2" "3"}}
>\textcolor{beaubleu}{ string1 <- c("a","ab","B","bba","one","!@","brute")}
>\textcolor{beaubleu}{ nchar(string1)   # Counts the number of symbols in each string.}
\textit{\textcolor{beauvert}{[1] 1 2 1 3 3 2 5}}
>\textcolor{beaubleu}{ string1[nchar(string1)>2]}
\textit{\textcolor{beauvert}{[1] "bba"   "one"   "brute"}}
>\textcolor{beaubleu}{ string2 <- c("e","D")}
>\textcolor{beaubleu}{ paste(string1,string2) # Concatenates the strings.}
\textit{\textcolor{beauvert}{[1] "a e"     "ab D"    "B e"     "bba D"   "one e"   "!@ D"   }}
\textit{\textcolor{beauvert}{[7] "brute e"}}
>\textcolor{beaubleu}{ paste(string1,string2,sep="-")  # A separator can be included}
\textcolor{beaubleu}{                                  # between the strings.}
\textit{\textcolor{beauvert}{[1] "a-e"     "ab-D"    "B-e"     "bba-D"   "one-e"   "!@-D"   }}
\textit{\textcolor{beauvert}{[7] "brute-e"}}
>\textcolor{beaubleu}{ paste(string1,string2,collapse="",sep="")  # collapse is used to }
\textcolor{beaubleu}{                                             # concatenate the elmts}
\textcolor{beaubleu}{                                             # into a single string.}
\textit{\textcolor{beauvert}{[1] "aeabDBebbaDonee!@Dbrutee"}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Manipulating character strings}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ substring("abcdef",first=1:3,last=2:4)}
\textit{\textcolor{beauvert}{[1] "ab" "bc" "cd"}}
>\textcolor{beaubleu}{ strsplit(c("05 Jan","06 Feb"), split=" ")}
\textit{\textcolor{beauvert}{[[1]]}}
\textit{\textcolor{beauvert}{[1] "05"  "Jan"}}
\textit{\textcolor{beauvert}{[[2]]}}
\textit{\textcolor{beauvert}{[1] "06"  "Feb"}}
>\textcolor{beaubleu}{ grep("i",c("Pierre","Benoit","Rems"))}
\textit{\textcolor{beauvert}{[1] 1 2}}
>\textcolor{beaubleu}{ gsub("i","L",c("Pierre","Benoit","Rems"))}
\textit{\textcolor{beauvert}{[1] "PLerre" "BenoLt" "Rems"  }}
>\textcolor{beaubleu}{ sub("r","L",c("Pierre","Benoit","Rems"))}
\textit{\textcolor{beauvert}{[1] "PieLre" "Benoit" "Rems"  }}
\end{Verbatim}

Perform the ``\textbf{Do it yourself}" on page 111.

\end{frame}

\begin{frame}[fragile]
\frametitle{Your turn to work!}

Do the Exercises on pages 134-136.\\
$ $\\
Do the Worksheet (A, B, E, C) on pages 136-140.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap5.pdf}\\


\end{frame}



\end{document}

