[1] "hello world"
[1] "hello world"
[1] "hello world"
[1] "hello world"
[1] "hello world"
Example: if I ask you to use the print() function to write “hello world” in the console 5 times, how would you do it?
What we are missing is a way to repeat a given operation without actually repeating the code manually.
There are several constructs that let us repeat operations; the most used are:
The for loop
The while loop
The repeat loop
The *apply family
for loopThe for loop is a structure that lets us repeat a portion of code a finite, pre-determined number of times.
A for loop is written as:
If I want to print something 5 times, I can simply use a for loop:
for loopfor(){ }: this is the implementation in R (similar to the if statement)
i: this is called the iterator or index. It is a generic index that can take any value and name. By convention it is called i, j etc. It keeps track of the number of iterations our loop has to do
in <values>: this indicates the values the iterator will take inside the loop
{ # operations }: these are the operations the loop must perform
The power of the for loop lies in the fact that the iterator i takes the values of the vector specified after in, one at a time:
For with an index vs withoutwhile loopThe while loop uses a logical condition instead of an iterator and a range of values as in the for loop. The loop keeps going as long as the condition is TRUE:
Try writing this while loop, see what happens and understand why
The while loop is not pre-determined, so it always needs a way to be stopped, by making the condition false.
repeat loopThe logic of the repeat loop is very similar to that of the while loop, but with 3 important differences:
it always performs at least one iteration
it emphasizes repetition until a condition is met
it uses the break command to stop
repeat loopRoll the die until a 6 comes up:
repeat vs. whilerepeat evaluates the condition at the end of the iteration, while while does it at the beginning. If the condition is not TRUE at the start, while does not run, whereas repeat does:
sum() functionImagine we did not have the sum() function and wanted to recreate it: how would we do it? Any ideas?
Let’s break the sum down conceptually; we add up the numbers from 1 to 10:
I take the first one and add it to the second (total = 1 + 2)
I take the total and add it to the 3rd element: total = total + 3 …
In practice we have:
our vector to sum
a total object that progressively accumulates the previous sums
Let’s put everything inside a function (i.e., I create a function that replicates what the sum function does)
The for loop is also useful, for example, to simulate data and perfom a power analysis. Suppose we have a variable y (income) that depends on age:
'data.frame': 30 obs. of 4 variables:
$ id : int 1 2 3 4 5 6 7 8 9 10 ...
$ age : int 36 29 37 49 33 50 16 24 48 46 ...
$ age_cat: chr "adult" "young" "adult" "adult" ...
$ age_z : num 0.27244 -0.35627 0.36226 1.44004 0.00299 ...
set.seed(111) # for reproducibility
#initialize the empity vectors
niter <- 1000 # number of iterations
res_all <- rep(NA, niter) # all estimated effects
p_val <- rep(NA, niter) # all p-values
for(i in 1:niter) {
y <- rnorm(nobs, mean = 0 + eff_age * age_z, sd = 1)
# linear model
mod <- lm(y ~ 1 + age_z)
# extract the effect estimate
res_all[i] <- coef(mod)[2]
# p-value of age_z
p_val[i] <- summary(mod)$coefficients[2, 4]
}Result:
Proportion significant = Power: 0.176
Mean of all effects: 0.1963144
Mean of significant effects: 0.450603
for loopsOnce you understand the iterative structure, you can easily extend it by putting a loop inside another one:
Two groups, Control and Treatment, with 3 participants each: a nested loop goes through every participant of every group.
[1] "Group: Control - Participant: 1"
[1] "Group: Control - Participant: 2"
[1] "Group: Control - Participant: 3"
[1] "Group: Treatment - Participant: 1"
[1] "Group: Treatment - Participant: 2"
[1] "Group: Treatment - Participant: 3"
For each group, the inner loop runs completely: 2 x 3 = 6 repetitions.
Now let’s simulate a reaction time (in ms) for each participant, and save it in a matrix: one row for each participant, one column for each group.
Control Treatment
1 NA NA
2 NA NA
3 NA NA
The two indices of the loops are the row (i) and the column (j) of the cell to fill: rt[i, j]
Control Treatment
1 569 482
2 472 470
3 518 445
Control Treatment
519.6667 465.6667
Open this link and keep it open: