\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\\ May 27, 2014\\
\vspace{1ex}
\url{https://biostatisticien.eu/springeR/courseRw3.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
\begin{itemize}
\item to enter data directly in \R;
\item to import or export data, to and from other software:
\begin{itemize}
\item Excel;
\item SPSS;
\item Minitab;
\item SAS;
\item Matlab.
\end{itemize}
\end{itemize}

\end{frame}

\section{Importing data}


\begin{frame}[fragile]
\frametitle{Importing data from a text file}

The three main \R functions to import data from a text file.
\begin{table}[ht]
\centering
\begin{tabular}{cp{7cm}}
\hline
\textbf{Function name} & \hspace*{3.5cm}\textbf{Description}\\
\hline
\hline
\commande{read.table()} & Best suited for data sets presented as tables, as it is often the case in Statistics.\\
\commande{read.ftable()} & Reads contingency tables.\\
\commande{scan()} & Much more flexible and powerful. Use this in all other cases.\\
\hline
\end{tabular}
\end{table}

\end{frame}


\begin{frame}[fragile]
\frametitle{Reading data with \texttt{read.table()}}

To read data present in an ASCII file:

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{my.data <- read.table(file=file.choose(),header=TRUE,}
\textcolor{beaubleu}{      sep="\mathem{\backslash}t",dec=".",row.names=1)}
\end{Verbatim}

\begin{table}[ht]
\centering
\begin{tabular}{cp{7cm}}
\hline
\textbf{Argument name} & \hspace*{3.5cm}\textbf{Description}\\
\hline
\hline
\commande{file}\texttt{=path/to/file} & Location and name of the file to be read.\\
\commande{header}\texttt{=TRUE} & Indicates whether the variable names are given on the first line of the file.\\

\commande{sep}\texttt{="$\backslash$t"} & The values on each line are separated by this character (\texttt{"$\backslash$t"}=\key{Tabulation}; \texttt{""}=whitespace; \texttt{","}=,; etc.).\\
\commande{dec}\texttt{="."} & Decimal mark for numbers (\texttt{"."} or \texttt{","}).\\ 
\commande{row.names}\texttt{=1} & 1st column of the file gives the individuals' names. \\
\hline
\end{tabular}
\end{table}



\end{frame}

\begin{frame}[fragile]
\frametitle{Reading data with \texttt{read.table()}}

The path can be specified explicitly: 

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{my.data <- read.table(file="C:/MyFolder/somedata.txt")}
\end{Verbatim}
or (doubling the backslashes):
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{my.data <- read.table(file="C:\mathem{\backslash}\mathem{\backslash}MyFolder\mathem{\backslash}\mathem{\backslash}somedata.txt")}
\end{Verbatim}
$ $\\
We can also use the function  \commande{setwd()} to change the work directory (equivalent to using the menu ``File/Change current directory''): 
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{setwd("C:/MyFolder")}
\textcolor{beaubleu}{my.file <- "mydata.txt"}
\textcolor{beaubleu}{data <- read.table(file=my.file)}
\textcolor{beaubleu}{head(data)}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Do it yourself}

You can perform the ``\textbf{Do it yourself}'' on page 66.

\end{frame}

\begin{frame}[fragile]
\frametitle{Reading data with \texttt{read.ftable()}}

To read contingency tables like this one:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
         "alcohol" "nondrinker" "occasional drinker" "regular drinker"
"GENDER" "tobacco"                                                                                 
"M"    "non-smoker"          6                19                  7
       "former smoker"       0                 9                  0
       "smoker"              1                 6                  5
"F"    "non-smoker"         12                26                  2
       "former smoker"       3                 5                  1
       "smoker"              1                 6                  1
\end{Verbatim}
use the instructions:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{Intima.table <- read.ftable("Intima_ftable.txt",}
\textcolor{beaubleu}{       row.var.names=c("GENDER","tobacco"),}
\textcolor{beaubleu}{       col.vars=list("alcohol"=c("nondrinker",}
\textcolor{beaubleu}{       "occasional drinker","regular drinker"))) }
\textcolor{beaubleu}{ftable(Intima.table)}
\end{Verbatim}

\end{frame}

\begin{frame}[fragile]
\frametitle{Reading data with the function \texttt{scan()}}

Function \texttt{scan()} should be used when the data are not organized as a rectangular table.\\
For example, suppose your data file contains the following lines:
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\scriptsize,fontseries=b]
File description:
-----------------------
The individual data are registered for nine variables 
in the following order:
GENDER AGE height weight tobacco packyear SPORT measure alcohol

Data:
--------
1 33 170 70 1 1 0 0,52 1 2 33 177 67 2 20 0 0,42 1
2 53 164 63 1 30 0 0,65 0 2 42 169
76 1 26 1 0,48 1
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Reading data with the function \texttt{scan()}}
Here are the commands we suggest you use to read this file. The argument \verb#skip=#$n$ is used to omit reading the first $n$ lines of the file.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{# Reading variable names:}
\textcolor{beaubleu}{variable.name <- scan("Intima_Media2.txt",skip=4,}
\textcolor{beaubleu}{                         nlines=1,what="")}
\textcolor{beaubleu}{# Reading data:}
\textcolor{beaubleu}{data <- scan("Intima_Media2.txt",skip=7,dec=",")}
\textcolor{beaubleu}{mytable <- as.data.frame(matrix(data,ncol=9,byrow=TRUE))}
\textcolor{beaubleu}{colnames(mytable) <- variable.name}
 \end{Verbatim}

\textbf{Note:} you can read data files directly from Internet with \texttt{read.table()} and \texttt{scan()}.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{read.table("http://www.biostatisticien.eu/springeR/}
\textcolor{beaubleu}{                   temperature.dat") }
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Importing data from Excel or the Open~Office spreadsheet}

\textbf{First approach: using copy-paste}\\
$ $\\

Using the mouse, select the range of the data (in the spreadsheet) which you wish to incorporate into \R. Once the data are selected, copy them to the clipboard (from the Edit menu, or with the keyboard shortcuts \key{Ctrl+C} on Windows or \key{Command+C} on a Mac).\\
$ $\\
All you need to do now is type the following instructions in the \R console to transfer the data from the clipboard.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{x <- read.table(file("clipboard"),sep="\mathem{\backslash}t",}
\textcolor{beaubleu}{                header=TRUE,dec=",")}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Importing data from Excel or the Open~Office spreadsheet}

\textbf{Second approach: Using an intermediary ASCII file}\\
$ $\\
Save your file in an ASCII format, then refer to the previous section.\\
$ $\\
\textbf{Third approach: Using specialized packages}\\
$ $\\
\begin{itemize}
\item Use function \commande{read.xls()} from package \commande{gdata} (needs PERL, can be installed on Windows via the file 
Rtools29.exe);
\item Use function \commande{read.xlsx()} from packages \commande{xlsx} or \commande{openxlsx}.
\end{itemize} 

\end{frame}

\begin{frame}[fragile]
\frametitle{Importing data from SPSS, Minitab, SAS or Matlab}

\begin{table}[ht]
\centering
\caption[Packages and \R importation functions from common software.]{Packages and \R importation functions from common software.}
\hspace*{-0.9cm}\begin{tabular}{c|c|c|c|c}
\hline
\textbf{Software} & \textbf{Package} & \textbf{\R function} & \textbf{File extension} & \textbf{Output format}\\
\hline
\hline
SPSS & \commande{foreign} & \commande{read.spss()} & \texttt{*.sav} & \texttt{list}\\
Minitab & \commande{foreign} & \commande{read.mtp()} & \texttt{*.mtp} & \texttt{list}\\
SAS & \commande{foreign} & \commande{read.xport()} & \texttt{*.xpt} & \texttt{data.frame}\\
Matlab & \commande{R.matlab} & \commande{readMat()} & \texttt{*.mat} & \texttt{list}\\
\hline
\end{tabular}
\end{table}


\end{frame}

\begin{frame}[fragile]
\frametitle{Large data files}

\R can handle large data sets quickly and efficiently. For this, you need to specify explicitly the type of each column using the argument \texttt{colClasses} (e.g., \texttt{=rep("character",3)}) of the function \texttt{read.table()}.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{tm <- Sys.time() # Gets the current time.}
\textcolor{beaubleu}{dbsnp <- read.table("dbsnp123.dat")}
\textcolor{beaubleu}{Sys.time() - tm}
\textit{\textcolor{beauvert}{Time difference of 5.063645 mins}}

\textcolor{beaubleu}{tm <- Sys.time()}
\textcolor{beaubleu}{dbsnp <- read.table("dbsnp123.dat",}
\textcolor{beaubleu}{          colClasses=rep("character",3))}
\textcolor{beaubleu}{Sys.time() - tm}
\textit{\textcolor{beauvert}{Time difference of 13.75810 secs}}
\end{Verbatim}

\end{frame}


\section{Exporting data}


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

\textbf{Exporting data to an ASCII text file:}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{write.table(mydata, file = "myfile.txt", sep = "\mathem{\backslash}t")}
\end{Verbatim}

\textbf{Exporting data to Excel or OpenOffice Calc:}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{X<-data.frame(Weight=c(80,90,75),Height=c(182,190,160))}
\textcolor{beaubleu}{write.table(X,file("clipboard"),sep="\mathem{\backslash}t",dec=".",}
\textcolor{beaubleu}{                                 row.names=FALSE)}
\end{Verbatim}
The data have now been copied to the clipboard. You can now paste them into your spreadsheet, for example by typing \texttt{Ctrl+V}.\\
$ $\\
See also the function \commande{write.xlsx()} from packages \commande{xlsx} or \commande{openxlsx}.


\end{frame}

\section{Creating data}


\begin{frame}[fragile]
\frametitle{Entering toy data: the \texttt{c()}, \texttt{seq()} and \texttt{:()} functions}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ c(1,5,8,2.3)}
\textit{\textcolor{beauvert}{[1] 1.0 5.0 8.0 2.3}}
>\textcolor{beaubleu}{ seq(from=4,to=5)}
\textit{\textcolor{beauvert}{[1] 4 5}}
>\textcolor{beaubleu}{ seq(from=4,to=5,by=0.1)}
\textit{\textcolor{beauvert}{ [1] 4.0 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5.0}}
>\textcolor{beaubleu}{ seq(from=4,to=5,length=8)}
\textit{\textcolor{beauvert}{[1] 4.000000 4.142857 4.285714 4.428571 4.571429 4.714286}}
\textit{\textcolor{beauvert}{[7] 4.857143 5.000000}}
>\textcolor{beaubleu}{ 1:12}
\textit{\textcolor{beauvert}{ [1]  1  2  3  4  5  6  7  8  9 10 11 12}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Entering toy data: the \texttt{rep()} function}

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ rep(1,4)}
\textit{\textcolor{beauvert}{[1] 1 1 1 1}}
>\textcolor{beaubleu}{ rep(1:4, 2)}
\textit{\textcolor{beauvert}{[1] 1 2 3 4 1 2 3 4}}
>\textcolor{beaubleu}{ rep(1:4, each = 2)}
\textit{\textcolor{beauvert}{[1] 1 1 2 2 3 3 4 4}}
>\textcolor{beaubleu}{ rep(1:4, c(2,1,2,3))}
\textit{\textcolor{beauvert}{[1] 1 1 2 3 3 4 4 4}}
>\textcolor{beaubleu}{ rep(1:4, each = 2, len = 4)   }
\textit{\textcolor{beauvert}{[1] 1 1 2 2}}
>\textcolor{beaubleu}{ rep(1:4, each = 2, len = 10)  }
\textit{\textcolor{beauvert}{ [1] 1 1 2 2 3 3 4 4 1 1}}
>\textcolor{beaubleu}{ rep(1:4, each = 2, times = 3)}
\textit{\textcolor{beauvert}{ [1] 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4 1 1 2 2 3 3 4 4}}
\end{Verbatim}

\end{frame}

\begin{frame}[fragile]
\frametitle{Generating pseudo-random numbers}

The function \commande{runif()} generates a sequence of randomly generated numbers (at uniform).
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ runif(5)}
\textit{\textcolor{beauvert}{[1] 0.4344968 0.7153407 0.4561363 0.9580362 0.7260245}}
>\textcolor{beaubleu}{ runif(5,min=2,max=7)}
\textit{\textcolor{beauvert}{[1] 5.634204 4.046403 5.415685 5.251441 2.209174}}
\end{Verbatim}


The function \commande{rnorm()} generates a sequence of random numbers from a normal distribution.
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
>\textcolor{beaubleu}{ rnorm(4)}
\textit{\textcolor{beauvert}{[1]  0.13585341 -0.09483162 -2.12326103  0.45974393}}
>\textcolor{beaubleu}{ rnorm(4,mean=2,sd=3)}
\textit{\textcolor{beauvert}{[1] -0.8673785  3.5660222  0.9401026  3.4794672}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Entering data from a hard copy}

$\bullet$ \textbf{Creating a vector with the function \commande{scan()}}\\

In this context, \commande{scan()} is more user-friendly than \commande{c()}. It can be used to easily enter data as you go.

\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
> \textcolor{beaubleu}{z <- scan() # R is waiting for you to enter data.}
\textit{\textcolor{beauvert}{1: }}\textcolor{beaubleu}{4.2}
\textit{\textcolor{beauvert}{2: }}\textcolor{beaubleu}{5.6}
\textit{\textcolor{beauvert}{3: }}\textcolor{beaubleu}{8.9}
\textit{\textcolor{beauvert}{4: }}\textcolor{beaubleu}{1}
\textit{\textcolor{beauvert}{5: }}\textcolor{beaubleu}{2.3}
\textit{\textcolor{beauvert}{6: }}\textcolor{beaubleu}{     # Press ENTER after an empty line}
\textcolor{beaubleu}{        # to halt the procedure.}
\textit{\textcolor{beauvert}{Read 5 items}}
> \textcolor{beaubleu}{z}
\textit{\textcolor{beauvert}{[1] 4.2 5.6 8.9 1.0 2.3}}
\end{Verbatim}


\end{frame}

\begin{frame}[fragile]
\frametitle{Entering data from a hard copy}

$\bullet$ \textbf{Creating several vectors of different lengths}\\


\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{data.entry("")}
\end{Verbatim}
You can change the names of the variables (columns) and enter data. Columns can contain different numbers of observations. If you leave the mini spreadsheet and type in the instruction \commande{ls()}, you will see the variables you have created.\\
$ $\\
$\bullet$ \textbf{Creating and individual$\times$variables table}\\

To enter data directly into \R's mini spreadsheet (as if using Excel), simply use the function \commande{de()} (for \textit{data entry}), as shown in the following instruction. 
\begin{Verbatim}[commandchars=\\\{\},fontfamily=courier,fontsize=\small,fontseries=b]
\textcolor{beaubleu}{X <- as.data.frame(de(""))}
\end{Verbatim}
Change the names of the variables and the types of the columns by clicking on the cells on the first row.

\end{frame}

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

You can now try to do the \textbf{Worksheet} of Chapter~4 (A and C) on pages 81--83.\\
$ $\\
\url{http://biostatisticien.eu/springeR/Rbook-chap4.pdf}\\
$ $\\


\end{frame}


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

\end{document}

