3 types of loops: for
while repeat
inside loops useful functions are:
next break
The structure of the for loop is illustrated:
sum1 <- sum2 <- 0
for (i in 1:200) {
sum1 <- sum1+1/i
sum2 <- sum2+(1/i)^2
}
The above is not good R programming though, such a computation is better done using vector-thinking:
sum1 <- 1/1:200; sum2 <- 1/(1:200)^2
Often as in the above example, for loops can be avoided by vector-thinking.
The syntax of a while loop:
i<- sum1 <- sum2 <- 0
while (i < 200) {
i <- i+1
sum1 <- sum1+1/i
sum2 <- sum2+(1/i)^2
}
and a repeat loop to do the above:
i <- sum1 <- sum2 <- 0
repeat {
i <- i+1
sum1 <- sum1+1/i
sum2 <- sum2+(1/i)^2
if (i >= 200) break()
}