Processing math: 100%
+ - 0:00:00
Notes for current slide
Notes for next slide

Experimental Design and Analysis





R session 01 - Introduction to R

Daniel Vaulot

2020-01-19




1 / 56

Experimental Design and Analysis

Outline - 3 sessions

  • 01 - Introduction to R
  • 02 - Data visualisation
  • 03 - R markdown
2 / 56

Experimental Design and Analysis

Outline - session 01

  • What is R and why use R ?
  • Resources
  • Get started
  • Fundamentals of R
    • Data objects
    • Vectors
    • Operators
    • Functions
    • Packages
    • Data frames
3 / 56

Introduction

  • Who has used R before ?
4 / 56

Introduction

  • Who has used R before ?

  • What other programming language have you used before ?

4 / 56

Introduction

  • Who has used R before ?

  • What other programming language have you used before ?

  • For those who are experts in R

4 / 56

Introduction

  • Who has used R before ?

  • What other programming language have you used before ?

  • For those who are experts in R

    • please refrain to answer during this session...
    • help your neighbor...
4 / 56

Introduction

  • Who has used R before ?

  • What other programming language have you used before ?

  • For those who are experts in R

    • please refrain to answer during this session...
    • help your neighbor...

  • Two special slide formatting

Your turn...

4 / 56

Introduction

  • Who has used R before ?

  • What other programming language have you used before ?

  • For those who are experts in R

    • please refrain to answer during this session...
    • help your neighbor...

  • Two special slide formatting

Your turn...

Warning

4 / 56

Introduction

Why use R ?

  • Script vs. Menu driven software (e.g. Excel)
    • Can be re-rerun with new data
    • Reproducible workflow
5 / 56

Introduction

Why use R ?

  • Script vs. Menu driven software (e.g. Excel)
    • Can be re-rerun with new data
    • Reproducible workflow
  • Open source
    • Huge number of libraries
    • Tidy "universe" : tidyverse and ggplot2
      • Very easy to manipulate tables (select columns, create new variables)
      • High quality graphics
5 / 56

Introduction

Why use R ?

  • Script vs. Menu driven software (e.g. Excel)
    • Can be re-rerun with new data
    • Reproducible workflow
  • Open source
    • Huge number of libraries
    • Tidy "universe" : tidyverse and ggplot2
      • Very easy to manipulate tables (select columns, create new variables)
      • High quality graphics
  • Work environment
    • R studio
5 / 56

Introduction

Why use R ?

  • Script vs. Menu driven software (e.g. Excel)
    • Can be re-rerun with new data
    • Reproducible workflow
  • Open source
    • Huge number of libraries
    • Tidy "universe" : tidyverse and ggplot2
      • Very easy to manipulate tables (select columns, create new variables)
      • High quality graphics
  • Work environment
    • R studio
  • Document your data processing
    • R markdown
    • Create HTML, pdf, presentations
5 / 56

Introduction

Why use R ?

  • Script vs. Menu driven software (e.g. Excel)
    • Can be re-rerun with new data
    • Reproducible workflow
  • Open source
    • Huge number of libraries
    • Tidy "universe" : tidyverse and ggplot2
      • Very easy to manipulate tables (select columns, create new variables)
      • High quality graphics
  • Work environment
    • R studio
  • Document your data processing
    • R markdown
    • Create HTML, pdf, presentations
  • Share your data and workflow
    • GitHub
5 / 56

Introduction

What can you do with R ?

6 / 56

Introduction

What can you do with R ?

  • Science
    • Statistics of course...
    • Data processing
    • Graphics
    • Time series analyses
    • Maps
    • Bioinformatics
6 / 56

Introduction

What can you do with R ?

  • Science
    • Statistics of course...
    • Data processing
    • Graphics
    • Time series analyses
    • Maps
    • Bioinformatics
  • But also
    • Teach
    • Do a presentation
    • Write your CV
    • Build a web site
    • Write a book
    • Much more...
6 / 56

Introduction

What can you do with R ?

  • Science
    • Statistics of course...
    • Data processing
    • Graphics
    • Time series analyses
    • Maps
    • Bioinformatics
  • But also
    • Teach
    • Do a presentation
    • Write your CV
    • Build a web site
    • Write a book
    • Much more...

6 / 56

Resources

Books and Manuals

  • Applied Statistics with R : Quite simple introduction with emphasis on Stats
  • R intro : Very good introduction to R, short and clear
  • R in a nutshell : Many many receipes to solve all your questions
  • R graphics cook book : very good for graphics
7 / 56

Resources

On line courses and web sites

8 / 56

Resources

Cheat sheets

9 / 56

Let's get started

Setup

11 / 56

Let's get started

The R studio interface

  • Bottom left
    • Console
  • Top left
    • File editor for .R and .Rmd files
    • Data frame visualization
  • Top right
    • Environment (i.e. R objects)
    • History
  • Bottom right
    • Files
    • Plots
    • Packages
    • Help
12 / 56

Let's get started

Create a new project

  • Open R studio
  • Create new project for the course in a new directory
    • e.g. Experimental design course
13 / 56

Let's get started

Your first script

print("Hello world")
[1] "Hello world"

Two ways to proceed

  1. Type directly in command window
14 / 56

Let's get started

Your first script

print("Hello world")
[1] "Hello world"

Two ways to proceed

  1. Type directly in command window

  2. Create a new script

Type in script window, select and execute (CTRL-R)

14 / 56

The R language

Everything in R is an object

  • Assignement done with <-
> x <- 1
> y <- 2
> x + y
[1] 3
15 / 56

The R language

Everything in R is an object

  • Assignement done with <-
> x <- 1
> y <- 2
> x + y
[1] 3
> z <- x + y
> z
[1] 3
15 / 56

The R language

= can be used instead of <- but refrain from it (not good style)

> z = x + y
16 / 56

The R language

= can be used instead of <- but refrain from it (not good style)

> z = x + y

You can view the values of the objects in R-studio environment window (top-right)

16 / 56

The R language

R is case sensitive

> Z
17 / 56

The R language

R is case sensitive

> Z
> Z
Error in eval(expr, envir, enclos): objet 'Z' introuvable
17 / 56

The R language

Rules for naming objects

  • Use
    • letters
    • numbers
    • the dot
    • the underscore (not the minus sign !)
  • Start always with a letter
    • Myvariable, Myvariable1, Myvariable.1,Myvariable-01 are OK
    • 1Myvariable, My-variable, Myvariable@ are not OK
18 / 56

The R language

Use consistent naming

Five conventions

  • alllowercase: e.g. adjustcolor
  • period.separated: e.g. plot.new
  • underscore_separated: e.g. numeric_version
  • lowerCamelCase: e.g. addTaskCallback
  • UpperCamelCase: e.g. SignatureMethod

Prefer third one, much more easy to read

  • Use names for objects : last_name
  • Use verbs for function : build_name
  • Think about best order
    • e.g. prefer maybe name_last because then you can have name_first, name_full...
    • and you identify that all these objects are related to a name...
19 / 56

R objects

Data types

  • character: "Daniel", "This is a course in R", 'Donald'

  • numeric: 2, 15.5, 10e-3

  • integer: 2L (the L tells R to store this as an integer)

  • date: 2018-02-25

  • logical: TRUE, FALSE

  • complex: 1+4i (complex numbers with real and imaginary parts)

20 / 56

R objects

Data types

  • character: "Daniel", "This is a course in R", 'Donald'

  • numeric: 2, 15.5, 10e-3

  • integer: 2L (the L tells R to store this as an integer)

  • date: 2018-02-25

  • logical: TRUE, FALSE

  • complex: 1+4i (complex numbers with real and imaginary parts)

  • No data "NA"

  • Not a number "NaN" (e.g. division by zero)

20 / 56

R objects

Data structures

  • Vector

  • List

  • Matrix

  • Data frames

  • Function

21 / 56

Vectors

The basic R structure is a vector: [102030]

22 / 56

Vectors

The basic R structure is a vector: [102030]

A vector can contain only a single element [10]

22 / 56

Vectors

The basic R structure is a vector: [102030]

A vector can contain only a single element [10]

Assign a value to a vector

x <- 10
x
[1] 10
22 / 56

Vectors

Assign several elements

x <- c(10, 20, 30)
x
[1] 10 20 30
23 / 56

Vectors

Assign several elements

x <- c(10, 20, 30)
x
[1] 10 20 30

Assign range

x <- 10:30
x
[1] 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
23 / 56

Vectors

Assign characters

PoTU <- c("Donald", "Trump")
PoTU
[1] "Donald" "Trump"

Assign logical

flags <- c(TRUE, FALSE, TRUE)
flags
[1] TRUE FALSE TRUE
24 / 56

Vectors

Access specific elements of a vector

First

x[1]
[1] 10
25 / 56

Vectors

Access specific elements of a vector

First

x[1]
[1] 10

Range

x[1:5]
[1] 10 11 12 13 14
25 / 56

Vectors

Access specific elements of a vector

First

x[1]
[1] 10

Range

x[1:5]
[1] 10 11 12 13 14

Remove one element

x[-1]
[1] 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
25 / 56

Vectors

Determine object properties

Apply functions (we will come back to functions latter)

  • typeof() - what is the object’s data type (low-level)?
  • length() - how long is it? What about two dimensional objects?
typeof(x)
length(x)
26 / 56

Vectors

Determine object properties

Apply functions (we will come back to functions latter)

  • typeof() - what is the object’s data type (low-level)?
  • length() - how long is it? What about two dimensional objects?
typeof(x)
length(x)
[1] "integer"
[1] 21
26 / 56

Vectors

Determine object properties

Apply functions (we will come back to functions latter)

  • typeof() - what is the object’s data type (low-level)?
  • length() - how long is it? What about two dimensional objects?
typeof(x)
length(x)
[1] "integer"
[1] 21

What is the type and length of PoTU ?

26 / 56

Operators

Arithmetic Operators

Operator Description
+ addition
- subtraction
* multiplication
/ division
^ or ** exponentiation
x %% y modulus (x mod y) 5%%2 is 1
x %/% y integer division 5%/%2 is 2
27 / 56

Operators

Arithmetic Operators

We are performing vector operations !

[123..]+[123..]=[246..]

28 / 56

Operators

Arithmetic Operators

Vector one element

x <- 1
y <- 2
z <- x + y
z
[1] 3
29 / 56

Operators

Arithmetic Operators

Vector several elements

# Two instructions on the same line
x <- 1:9; y <- 1:9
z <- x + y
z
[1] 2 4 6 8 10 12 14 16 18
30 / 56

Operators

Arithmetic Operators

Vector several elements

# Two instructions on the same line
x <- 1:9; y <- 1:9
z <- x + y
z
[1] 2 4 6 8 10 12 14 16 18
  • Several instructions on same line separate by ;
  • The hastag # indicate a comment -> Use heavily to document your code
  • However, it is even better to use R markdown (see next class)
30 / 56

Operators

Arithmetic Operators

Vector several elements

# Two instructions on the same line
x <- 1:9; y <- 1:9
z <- x + y
z
[1] 2 4 6 8 10 12 14 16 18
  • Several instructions on same line separate by ;
  • The hastag # indicate a comment -> Use heavily to document your code
  • However, it is even better to use R markdown (see next class)

Use the other operators

30 / 56

Operators

Arithmetic Operators

What happens when the vectors have different number of elements ?

x <- 1:9
y <- 1
z <- x + y
z
31 / 56

Operators

Arithmetic Operators

What happens when the vectors have different number of elements ?

x <- 1:9
y <- 1
z <- x + y
z
[1] 2 3 4 5 6 7 8 9 10
31 / 56

Operators

Arithmetic Operators

What happens when the vectors have different number of elements ?

x <- 1:9
y <- 1
z <- x + y
z
[1] 2 3 4 5 6 7 8 9 10

Equivalent to

y <- c(1, 1, 1, 1, 1, 1, 1, 1, 1)

The recycling rule...

31 / 56

Operators

Can we add logical ?

x <- TRUE
y <- FALSE
z <- x + y
z
32 / 56

Operators

Can we add logical ?

x <- TRUE
y <- FALSE
z <- x + y
z
[1] 1
32 / 56

Operators

Can we add logical ?

No error but...

The resulting variable is transformed to a numeric

How you would show that ?

33 / 56

Operators

Can we add logical ?

No error but...

The resulting variable is transformed to a numeric

How you would show that ?

typeof(x)
[1] "logical"
typeof(z)
[1] "integer"
33 / 56

Operators

Logical Operators

Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
!x Not x
x | y x OR y
x & y x AND y
isTRUE(x) test if X is TRUE
34 / 56

Operators

Logical Operators

x <- TRUE
y <- FALSE
z1 <- x | y
z2 <- x == y
35 / 56

Operators

Logical Operators

x <- TRUE
y <- FALSE
z1 <- x | y
z2 <- x == y
[1] TRUE
[1] FALSE

Do not mix

  • == which is logical operator
  • = which is assignement
35 / 56

Operators

Can we add characters ?

first <- "Donald"
last <- "Trump"
full <- first + last
36 / 56

Operators

Can we add characters ?

first <- "Donald"
last <- "Trump"
full <- first + last

Generates an error

Error in first + last: argument non numérique pour un opérateur binaire
36 / 56

Operators

Can we add characters ?

first <- "Donald"
last <- "Trump"
full <- first + last

Generates an error

Error in first + last: argument non numérique pour un opérateur binaire

What can we do ?

36 / 56

Functions

Function perform specific task on objects

  • e.g. to concatanate strings we use paste0()
37 / 56

Functions

Function perform specific task on objects

  • e.g. to concatanate strings we use paste0()
paste0(first, last)
[1] "DonaldTrump"
37 / 56

Functions

Function perform specific task on objects

  • e.g. to concatanate strings we use paste0()
paste0(first, last)
[1] "DonaldTrump"
  • Functions take arguments and return an object called result

  • To know the arguments use ?

? paste0() # Do not forget the parenthesis
37 / 56

Functions

Function perform specific task on objects

  • e.g. to concatanate strings we use paste0()
paste0(first, last)
[1] "DonaldTrump"
  • Functions take arguments and return an object called result

  • To know the arguments use ?

? paste0() # Do not forget the parenthesis

What happened ?

37 / 56

Functions

Function perform specific task on objects

  • e.g. to concatanate strings we use paste0()
paste0(first, last)
[1] "DonaldTrump"
  • Functions take arguments and return an object called result

  • To know the arguments use ?

? paste0() # Do not forget the parenthesis

What happened ?

  • Can go directly to Help panel and type function name
37 / 56

Functions

Help

38 / 56

Functions

Help

39 / 56

Functions

Getting what you want

We would like to write "Donald Trump" but we have :

paste0(first, last)
[1] "DonaldTrump"

Can you read the help and suggest a change in the way we call the function ?

40 / 56

Functions

Getting what you want

We would like to write "Donald Trump" but we have :

paste0(first, last)
[1] "DonaldTrump"

Can you read the help and suggest a change in the way we call the function ?

paste(first, last)
[1] "Donald Trump"
40 / 56

Functions

Write your own function

my_sum <- function(a, b) {
c <- a + b
return(c)
}
41 / 56

Functions

Write your own function

my_sum <- function(a, b) {
c <- a + b
return(c)
}
my_sum(10, 20)
[1] 30

If you write 3 times the same piece of code write a function...

41 / 56

Functions

Examples of functions

Most of the time you do not have to write functions because someone has already written one for what you want to do...

  • Sum
x <- 1:100
sum(x)
[1] 5050
42 / 56

Functions

Examples of functions

Most of the time you do not have to write functions because someone has already written one for what you want to do...

  • Sum
x <- 1:100
sum(x)
[1] 5050
  • Normal distribution
y <- rnorm(10, mean = 0, sd = 1)
y
[1] -1.13613929 0.63692448 -0.07460907 0.72597733 -1.24725670 0.07377771
[7] 0.40098213 0.74694020 -0.12867386 0.45170224
42 / 56

Functions

Statistics

mean(y)
[1] 0.04496252
sd(y)
[1] 0.7233617
43 / 56

Functions

Statistics

mean(y)
[1] 0.04496252
sd(y)
[1] 0.7233617

Sample more points... 10,000 instead of 100

y <- rnorm(10000, mean = 0, sd = 1)
mean(y)
[1] 0.01063662
sd(y)
[1] 0.9987526
43 / 56

Functions

Plot

Histogram

library(graphics)
hist(y)

  • What is this "library()"
44 / 56

Packages

Packages are set of functions that have a common goal

They are really the strength of R

And these are only the "official"" packages. You can find more on GitHub

45 / 56

Packages

Installing a package

Download on your computer the package you need

Install package stringr (to manipulate strings of characters)

46 / 56

Packages

Using a package

To use functions from the package

  • use the syntax package::function
stringr::str_c(first, last, sep = " ")
[1] "Donald Trump"
47 / 56

Packages

Using a package

To use functions from the package

  • use the syntax package::function
stringr::str_c(first, last, sep = " ")
[1] "Donald Trump"
  • load the package with the library function
library(stringr)
str_c(first, last, sep = " ")
[1] "Donald Trump"
47 / 56

Packages

Using a package

To use functions from the package

  • use the syntax package::function
stringr::str_c(first, last, sep = " ")
[1] "Donald Trump"
  • load the package with the library function
library(stringr)
str_c(first, last, sep = " ")
[1] "Donald Trump"

Sometimes functions from different libraries have similar names

47 / 56

Packages

List installed packages

48 / 56

Other objects

  • List

  • Matrix

  • Factors

  • Data frames

49 / 56

Data frames

What is it ?

  • Table mixing different types of columns (an Excel table...)
  • However within a column all values are similar, e.g. numeric, logical, character
50 / 56

Data frames

What is it ?

  • Table mixing different types of columns (an Excel table...)
  • However within a column all values are similar, e.g. numeric, logical, character
df <- data.frame(label = letters[1:6], id = 1:6, value = rnorm(6, mean = 0, sd = 1),
flag = c(TRUE, FALSE), stringsAsFactors = FALSE)
df
label id value flag
1 a 1 0.1176364 TRUE
2 b 2 -1.1298893 FALSE
3 c 3 0.5195048 TRUE
4 d 4 -0.7246693 FALSE
5 e 5 0.5171964 TRUE
6 f 6 1.3644754 FALSE
  • We will not get into the factor at this time, why we set stringsAsFactors = FALSE
  • Notice the recycling rule ?
50 / 56

Data frames

Useful functions

dim(df) # returns the dimensions of data frame
[1] 6 4
nrow(df) # number of rows
[1] 6
ncol(df) # number of columns
[1] 4
51 / 56

Data frames

Useful functions

str(df) # structure of data frame - name, type and preview of data in each column
'data.frame': 6 obs. of 4 variables:
$ label: chr "a" "b" "c" "d" ...
$ id : int 1 2 3 4 5 6
$ value: num 0.118 -1.13 0.52 -0.725 0.517 ...
$ flag : logi TRUE FALSE TRUE FALSE TRUE FALSE
colnames(df) # columns names
[1] "label" "id" "value" "flag"
52 / 56

Data frames

Access specific column

  • Use $notation
df$value
[1] 0.1176364 -1.1298893 0.5195048 -0.7246693 0.5171964 1.3644754
53 / 56

Data frames

Access specific column

  • Use $notation
df$value
[1] 0.1176364 -1.1298893 0.5195048 -0.7246693 0.5171964 1.3644754
  • Use the df[i,j] notation
df[, 3]
[1] 0.1176364 -1.1298893 0.5195048 -0.7246693 0.5171964 1.3644754
df[, "value"]
[1] 0.1176364 -1.1298893 0.5195048 -0.7246693 0.5171964 1.3644754
53 / 56

Data frames

Access specific value

  • $ for the column, [i] for the row
df$label[5]
[1] "e"
df$label[1:5]
[1] "a" "b" "c" "d" "e"
54 / 56

Data frames

Access specific value

  • $ for the column, [i] for the row
df$label[5]
[1] "e"
df$label[1:5]
[1] "a" "b" "c" "d" "e"
  • Use the df[i,j] notation, first index corresponds to row, second index to column
df[5, 1]
[1] "e"
df[1:5, "value"]
[1] 0.1176364 -1.1298893 0.5195048 -0.7246693 0.5171964
54 / 56

Data frames

Filter the data

df[df$id <= 3, ]
label id value flag
1 a 1 0.1176364 TRUE
2 b 2 -1.1298893 FALSE
3 c 3 0.5195048 TRUE

Select lines for which the label is c

55 / 56

Data frames

Filter the data

df[df$id <= 3, ]
label id value flag
1 a 1 0.1176364 TRUE
2 b 2 -1.1298893 FALSE
3 c 3 0.5195048 TRUE

Select lines for which the label is c

df[df$label == "c", ]
label id value flag
3 c 3 0.5195048 TRUE
55 / 56

What did you learn ?

  • Objects: data types vs data structures
56 / 56

What did you learn ?

  • Objects: data types vs data structures
  • Vectors: think in vector operations
56 / 56

What did you learn ?

  • Objects: data types vs data structures
  • Vectors: think in vector operations
  • Operators: arithmetic vs. logical
56 / 56

What did you learn ?

  • Objects: data types vs data structures
  • Vectors: think in vector operations
  • Operators: arithmetic vs. logical
  • Functions: Try to practice
56 / 56

What did you learn ?

  • Objects: data types vs data structures
  • Vectors: think in vector operations
  • Operators: arithmetic vs. logical
  • Functions: Try to practice
  • Data frames: most useful objects (Excel type)
56 / 56

Experimental Design and Analysis

Outline - 3 sessions

  • 01 - Introduction to R
  • 02 - Data visualisation
  • 03 - R markdown
2 / 56
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow