You are on page 1of 21

# Lecture 6: loops

,
control structures & apply family
Simeon Lisovski
Ben Fanson
… last week … dplyr
1) introduce the grammar of data manipulation

2) table verbs

3) building sentences

4) restructuring

… 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' )
… this week …
1) loops (for, while, repeat)
2) Control structure (if… else)
3) Loop families (apply, lapply, tapply)
For Loops
for (<index> in <vector>) {
<statements>
}
the <vector> determines what value <index> will take in a loop
• The loop is performed length(vector) times
• On the n’th iteration of the loop, var takes the value vector[n]
• indexis a completely new variable and not directly related to anything
other variable
Control structures
if (<logical expression>) {
<statements>
}
Sometimes, a block of code should be executed only if a certain
condition is satisfied. In this case, the if structure can be used:
Control structures
You will often need to distinguish between several cases. In
this case, you can extend the if structure by one or more else
clauses
if (<logical expression>) {
<statements>
} else {
<statements>
}
while() and repeat() loops
while (<logical expression>) {
<statements>
}
repeat {
<statements>
if (<logical expression>) break
}
Another loop structure provided by R is
the repeat structure. This structure
repeats the commands in its body until a
break statement is reached
One of the simplest looping
structures is the while loop. Here,
the <statements> will be executed
until <logical expression> is FALSE.

Be aware of infinite loops.
apply Family
apply Family
apply Family
A B C
ds =
apply Family
A B C
ds =
ds %.%
mutate( D = mean(C) )
apply Family
ds %.%
mutate( D = mean(C) )
A B C
ds =
D
apply(ds\$C, 2, mean)
ds\$D <- apply(ds\$C, 2, mean)
apply(ds\$C, 2, mean)
ds\$D <- apply(ds\$C, 2, mean)
ds %.%
mutate( D = mean(C) )
apply Family
A B C
ds =
D
apply(ds, 2, mean)
ds\$D <- apply(ds, 2, mean)
apply Family
ds %.%
mutate( D = mean(C) )
A B C
ds =
mean
median
max
min
length
as.character
as.numeric
as.factors
is.na

apply(ds\$C, 2, mean)
ds\$D <- apply(ds\$C, 2, mean)
apply(ds, 2, mean)
ds\$D <- apply(ds, 2, mean)
apply(ds, 1, mean)
apply Family
A B C
ds =
D
1
1
2
2
tapply(ds\$C, ds\$D, mean)
apply Family
A B C
lst[[1]] =
lst =
A B C
lst[[2]] =
result <- lapply(lst, mean)
result =
result[[1]] = mean(lst[[1]])
result[[2]] = mean(lst[[2]])
apply Family
A B C
lst[[1]] =
lst =
A B C
lst[[2]] =
result = c(mean(lst[[1]], mean(lst[[2]]) result <- sapply(lst, mean)
Lecture 6: Hands on Section
1) get Lecture6.R from github

- lots of data for todays ‘hands on section’ will be simulated.

Lecture 6 files