\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\\ July 1, 2014\\
\vspace{1ex}
\url{https://biostatisticien.eu/springeR/courseRw7.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 developing functions;
\item debugging functions;
\item managing sessions;
\item making \R packages.
\end{itemize}

\end{frame}


\section{Developing functions}


\begin{frame}[fragile]
\frametitle{Quick start}


Declaring a function is done with the following general form:\\
\centerline{\texttt{function(<list of arguments>) <body of the function>}}
where
\begin{itemize}
\item \texttt{<list of arguments>} is a list of named (formal) arguments;
\item \texttt{<body of the function>} represents, as the name suggests, the contents of the code to execute when the function is called. 
\end{itemize}

Here is an example of function declaration:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ function(name) cat("Hello",name,"!")}
\textit{\textcolor{beauvert}{function(name) cat("Hello",name,"!")}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Quick start}

For \R, a function is a specific object.  Creating a function thus corresponds to affecting the object ``\R~function'' to a variable, the name of which corresponds to the function itself.  For example, to create the function \texttt{hello()}, you can proceed as follows:

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello <- function(name) cat("Hello",name,"!")}
>\textcolor{beaubleu}{ hello}
\textit{\textcolor{beauvert}{function(name) cat("Hello",name,"!")}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Quick start}

For this function to be executed, the user needs to call the function, followed by the effective arguments listed in brackets.  Recall that an \textbf{effective argument}\index{effective argument} is the value affected to a formal argument\index{formal arguments}.  We will use the terms calling argument and input argument as synonyms of effective argument. 

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello("Peter")}
\textit{\textcolor{beauvert}{Hello Peter !}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Body of a function}

The body\index{functions!body} of a function can be a simple \R instruction, or a sequence of \R instructions. \index{functions!sequence of instructions} In the latter case, the instructions must be enclosed between the characters \commande{\{} and \commande{\}} to delimit the beginning and end of the body of the function. 
Several \R instructions can be written on the same line as long as they are separated by the character \commande{;}.  
When the body of the function includes several \R instructions written on the same line, do not forget to enclose them between characters \commande{\{} and \commande{\}}. 
Recall that on a line, any code written after the character \commande{\#} is not interpreted by \R and is taken to be a comment. \index{functions!comments} 

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
>\textcolor{beaubleu}{ hello <- function(name) \{}
+\textcolor{beaubleu}{   # Convert the name to upper case. }
+\textcolor{beaubleu}{   name <- toupper(name)}
+\textcolor{beaubleu}{   cat("Hello",name,"!") }
+\textcolor{beaubleu}{ \}}
>\textcolor{beaubleu}{ hello("Peter")}
\textit{\textcolor{beauvert}{Hello PETER !}}
\end{Verbatim}



\end{frame}

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

When declaring a function, \textbf{all arguments are identified by a unique name}.  Each argument can be associated with a default value.  To specify a default value, use the character \commande{=} followed by the default value, as when declaring a list object  (\commande{list}). 
When the function is called with no effective argument for that argument, the default value will be used.  We have used this functionality many times in previous chapters, but we now know how to include it when developing new functions.  Here is an example:

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello <- function(name="Peter") cat("Hello",name,"!")}
>\textcolor{beaubleu}{ hello()}
\textit{\textcolor{beauvert}{Hello Peter !}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Naming effective arguments}

In \R, an effective argument can be entered by adding the name of the formal argument.  Of course, this is of little interest when the function only depends on a single formal argument.  Let us add to our function \texttt{hello()} the possibility of choosing a language, and see a few calls of this function. 
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello <- function(name="Peter",language="eng") \{}
+\textcolor{beaubleu}{   cat(switch(language,fr="Bonjour",sp="Hola",}
+\textcolor{beaubleu}{              eng="Hello"),name,"!")}
+\textcolor{beaubleu}{ \}}
>\textcolor{beaubleu}{ hello()}
\textit{\textcolor{beauvert}{Hello Peter !}}
>\textcolor{beaubleu}{ hello(name="Ben")}
\textit{\textcolor{beauvert}{Hello Ben !}}
>\textcolor{beaubleu}{ hello(language="fr")}
\textit{\textcolor{beauvert}{Bonjour Peter !}}
\end{Verbatim}



\end{frame}

\begin{frame}[fragile]
\frametitle{Partial naming of effective arguments}

In the same context, a second functionality of \R is that it allows calling a function without typing in the complete name of a formal argument.  Consider the following calls of the function  \texttt{hello()}:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello(lang="eng")}
\textit{\textcolor{beauvert}{Hello Peter !}}
>\textcolor{beaubleu}{ hello(l="eng")}
\textit{\textcolor{beauvert}{Hello Peter !}}
>\textcolor{beaubleu}{ hello(l="e")}
\textit{\textcolor{beauvert}{ Peter !}}
\end{Verbatim}

The rule for determining the formal argument corresponding to a partial name is: in the ordered list of formal arguments of the function, the selected formal argument is the \textbf{first} formal argument for which there is a match between the first letters of the argument name and the partial name given by the user. \\



\end{frame}

\begin{frame}[fragile]
\frametitle{List of supplementary arguments ``\texttt{...}''}

You can give a list of supplementary arguments with the syntax \commande{...}.  When calling the function, all ``named'' arguments which are not in the list of formal arguments are grouped in the structure \commande{...}.  In the body of the function, the user can then use the syntax \commande{...} as if copy-pasting the list of supplementary named arguments.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
>\textcolor{beaubleu}{ test.3points <- function(a="foo",...) print(list(a=a,...))}
>\textcolor{beaubleu}{ test.3points("bar",b="foo")}
\textit{\textcolor{beauvert}{$a}}
\textit{\textcolor{beauvert}{[1] "bar"}}
\textit{\textcolor{beauvert}{$b}}
\textit{\textcolor{beauvert}{[1] "foo"}}
\end{Verbatim}

Unless for very specific purpose, use \commande{...} as the last formal argument.



\end{frame}

\begin{frame}[fragile]
\frametitle{Object returned by a function}

The function \texttt{hello()} does not return any object.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ res <- hello()}
\textit{\textcolor{beauvert}{Hello Peter !}}
>\textcolor{beaubleu}{ res}
\textit{\textcolor{beauvert}{NULL}}
\end{Verbatim}


A general rule to return an object is to use the function \commande{return()}.  This instruction halts the execution of the code of the body of the function and returns the object between brackets.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ hello <- function(name="Peter") \{}
+\textcolor{beaubleu}{   return(paste("Hello",name,"!",collapse=" "))\}}
>\textcolor{beaubleu}{ hello()}
\textit{\textcolor{beauvert}{[1] "Hello Peter !"}}
>\textcolor{beaubleu}{ message <- hello()}
>\textcolor{beaubleu}{ message}
\textit{\textcolor{beauvert}{[1] "Hello Peter !"}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Variable scope in the body of a function}

The notion of variable scope is very important for a language which allows to develop functions.  The main point is that variables defined inside the body of a function have a local scope during function execution.  This means that a variable inside the body of a function is physically different from another variable with the same name, but defined in the workspace of your \R session.  Generally speaking, local scope means that a variable only exists inside the body of the function.  After the execution of the function, the variable is thus automatically deleted from the memory of the computer. 


\end{frame}

\begin{frame}[fragile]
\frametitle{Scope of variables}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\tiny,fontseries=b]
>\textcolor{beaubleu}{ message <- "hello Pierre !"}
>\textcolor{beaubleu}{ message # Workspace initialization. }
\textit{\textcolor{beauvert}{[1] "hello Pierre !"}}
>\textcolor{beaubleu}{ hello <- function(name="Peter",message="hello") \{}
+\textcolor{beaubleu}{   print(message)}
+\textcolor{beaubleu}{   message <- paste(message,name,"!",collapse=" ")}
+\textcolor{beaubleu}{   print(message)}
+\textcolor{beaubleu}{   invisible(message)}
+\textcolor{beaubleu}{ \}}
>\textcolor{beaubleu}{ hello()}
\textit{\textcolor{beauvert}{[1] "hello"}}
\textit{\textcolor{beauvert}{[1] "hello Peter !"}}
>\textcolor{beaubleu}{ message # Workspace has not been modified!}
\textit{\textcolor{beauvert}{[1] "hello Pierre !"}}
>\textcolor{beaubleu}{ message <- hello()}
\textit{\textcolor{beauvert}{[1] "hello"}}
\textit{\textcolor{beauvert}{[1] "hello Peter !"}}
>\textcolor{beaubleu}{ message # Workspace has been modified!}
\textit{\textcolor{beauvert}{[1] "hello Peter !"}}
>\textcolor{beaubleu}{ message <- hello(message="Welcome")}
\textit{\textcolor{beauvert}{[1] "Welcome"}}
\textit{\textcolor{beauvert}{[1] "Welcome Peter !"}}
>\textcolor{beaubleu}{ message # Workspace has been modified again!}
\textit{\textcolor{beauvert}{[1] "Welcome Peter !"}}
\end{Verbatim}


\end{frame}


\section{Debugging functions}


\begin{frame}[fragile]
\frametitle{The function \commande{browser()}}

A useful debugging function in \R is the function \commande{browser()}.  
If you insert the instruction \commande{browser()} in the source of your function, the program will stop at the place where it was inserted.\\
$ $\\

By typing the letter \commande{n} (for \textit{next}), you can inspect the code and the contents of variables sequentially. 
To leave the inspection mode, type  \commande{Q}. 


\end{frame}

\begin{frame}[fragile]
\frametitle{The function \commande{debug()}}

Another interesting function is  \commande{debug()} which is equivalent to putting the instruction \commande{browser()} at the top of a function.  Thus \verb#debug(var)# marks the functions \verb#var# as debuggable.  Any subsequent call of this function will launch the online debugger\index{debugger}. 

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{debug(var)}
\textcolor{beaubleu}{var(1:3)}
\end{Verbatim}


To get rid of this mark, use the  function \commande{undebug()}. 

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{undebug(var)}
\end{Verbatim}



\end{frame}

\section{Managing sessions}

\begin{frame}[fragile]
\frametitle{Listing and deleting objects}

After you have created \R objects, you can get the list of all objects with the function \commande{ls()} or the synonymous function \commande{objects()}.\\
$ $\\
To delete objects, use the function \commande{rm()}.\\
$ $\\
It is worth noting that the command \commande{getwd()} returns the current working directory\index{directory}. The command \commande{setwd()} is used to change working directory.




\end{frame}

\begin{frame}[fragile]
\frametitle{Workspace: .RData files}

When working with \R, objects are created: vectors, matrices, functions, etc. These objects are physically saved in a file on the hard disk called \textbf{workspace}. The file name extension must be  \verb#.RData#.\\

It is possible to create several \verb#.RData# files: one for each project you are working on. You should create these \verb#.RData# files in different appropriate folders. For example, suppose you are working on two different projects: one related to cars and one related to climate events. You could then create a folder called \texttt{Cars} containing a file \texttt{cars.RData}, and another folder called \texttt{Climate} containing a file called \texttt{climevt.RData}; these files will contain the \R objects corresponding to the two studies.


The function \commande{save.image()} is used to save\index{saving} a workspace; you can use the   function \commande{load()} to load an existing workspace.


\end{frame}

\begin{frame}[fragile]
\frametitle{.RData files}

Perform the ``Do it yourself'' on page 286.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap9.pdf}\\



\end{frame}

\begin{frame}[fragile]
\frametitle{Command history}

\R includes a mechanism to recall and reexecute old commands. The \verb#up# and \verb#down# arrows on the keyboard can be used to go back and forward in the command history. Once you have located a command using this method, you can move the cursor using the \verb#right# and \verb#left# arrows, delete characters with the \key{DEL} key, and add or modify characters with the keyboard.\\
$ $\\


To save the command history of the current session, use the command \commande{savehistory()}. To load the command history from a previous session, use the command \commande{loadhistory()}. The commands are saved in a file which must have the extension \verb#.Rhistory# (or \verb#.rhi# in old versions of \R).


\end{frame}

\section{Managing packages}


\begin{frame}[fragile]
\frametitle{Managing packages}

A package is a collection of data and functions belonging to a same theme. 
When you install \R, some basic functionalities come out of the box. But you can extend the functionalities of \R by adding libraries, also called packages. 
First, install the package on the computer's hard disk, then load (activate) it in the memory of \R only when needed (see Appendix A for further details).\\
$ $\\

The function \commande{search()} gives the list of databases (collections of \R packages) attached to the system. The function \commande{searchpaths()} returns the same list, but adds the path to the corresponding file.\\
$ $\\

The function \commande{library()} returns the list of all packages installed on disk.


\end{frame}


\begin{frame}[fragile]
\frametitle{.RData files}

Perform the ``Do it yourself'' on page 291.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap9.pdf}\\



\end{frame}



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

Do the Exercises and the Worksheet on pages 306--309.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap9.pdf}\\


\end{frame}


% \bibliographystyle{jss}
% \bibliography{biblio}

\end{document}

