r course 2014: lecture 6
TRANSCRIPT
-
8/10/2019 R Course 2014: Lecture 6
1/21
Lecture 6: loops,control structures & apply fam
Simeon Lisovski
Ben Fanson
-
8/10/2019 R Course 2014: Lecture 6
2/21
last week dplyr
1) introduce the grammar of data manipulation
2) table verbs
3) building sentences
4) restructuring
-
8/10/2019 R Course 2014: Lecture 6
3/21
last week dplyr
ds %.%select(treatment, growth_rate) %.%
group_by(treatment) %.%
mutate( mean_growth = mean(growth_rate) )
ds %.%
select(treatment, growth_rate) %.%
mutate( growth_rate2 = growth_rate ^2 ) %.%
filter( treatment == 't1' )
-
8/10/2019 R Course 2014: Lecture 6
4/21
this week
1) loops (for, while, repeat)
2) Control structure (if else)
3) Loop families (apply, lapply, tapply)
-
8/10/2019 R Course 2014: Lecture 6
5/21
For Loops
for ( in ) {
}
the determines what value will take The loop is performed length(vector) times
On the nthiteration of the loop, var takes the value vector[n]
indexis a completely new variable and not directly related to anythingother variable
-
8/10/2019 R Course 2014: Lecture 6
6/21
Control structures
if () {
}
Sometimes, a block of code should be executed only if
condition is satisfied. In this case, the if structure can
-
8/10/2019 R Course 2014: Lecture 6
7/21
Control structuresYou will often need to distinguish between several cas
this case, you can extend the if structure by one or mo
clauses
if () {
} else {
}
-
8/10/2019 R Course 2014: Lecture 6
8/21
while() and repeat() loo
while () {
}
repeat {
if (
-
8/10/2019 R Course 2014: Lecture 6
9/21
-
8/10/2019 R Course 2014: Lecture 6
10/21
apply Family
-
8/10/2019 R Course 2014: Lecture 6
11/21
apply Family
http://adv-r.had.co.nz/Data-st
-
8/10/2019 R Course 2014: Lecture 6
12/21
apply Family
A B C
ds =
-
8/10/2019 R Course 2014: Lecture 6
13/21
apply Family
A B C
ds =
ds %.%
mutate( D = mean(C) )
-
8/10/2019 R Course 2014: Lecture 6
14/21
apply Familyds %.%
mutate( D = mean(C) )A B C
ds =
D
apply(ds$C, 2, mean)
ds$D
-
8/10/2019 R Course 2014: Lecture 6
15/21
apply(ds$C, 2, mean)
ds$D
-
8/10/2019 R Course 2014: Lecture 6
16/21
apply Familyds %.%
mutate( D = mean(C) )A B C
ds =
apply(ds$C, 2, mean)
ds$D
-
8/10/2019 R Course 2014: Lecture 6
17/21
apply Family
A B C
ds =
D
1
1
2
2
tapply(ds$C, ds$D, mean)
-
8/10/2019 R Course 2014: Lecture 6
18/21
apply FamilyA B C
lst[[1]] =
lst =
A B C
lst[[2]] =
result
-
8/10/2019 R Course 2014: Lecture 6
19/21
apply FamilyA B C
lst[[1]] =
lst =
A B C
lst[[2]] =
result = c(mearesult
-
8/10/2019 R Course 2014: Lecture 6
20/21
Lecture 6: Hands on Sectio
-
8/10/2019 R Course 2014: Lecture 6
21/21
1) get Lecture6.Rfrom github
- lots of data for todays hands on section will be simulated.
Lecture 6 files