With a while instruction you can also implement a restricted repetition, where the number of repetitions is fixed in advance. The example below shows how to calculate the sum of the first 10 natural numbers.

> sum_of_numbers <- 0
> n <- 1
> while (n < 11) {
+   sum_of_numbers <- sum_of_numbers + n
+   n <- n + 1
+ }
> cat("sum from 1 through 10 equals", sum_of_numbers, "\n")
sum from 1 through 10 equals 55 

But the for statement is more common to implement a restricted repetition. The example above goes like this:

> sum_of_numbers <- 0
> for (i in 1:10) { sum_of_numbers <- sum_of_numbers + i }
> cat("sum from 1 through 10 equals", sum_of_numbers, "\n")
sum from 1 through 10 equals 55 

The general form of a by counting restricted repetition (for instruction via a vector object) is below; read the explanation.

By counting restricted repetition

for (counting_variable in seq(from = start, to = end , by = stepsize)) {
indented instructions
}

You can also apply repetitions in a nested manner. The example below shows a program to construct a so-called Vandermonde matrix.

Example of nested repetition
> M <- matrix(0, nrow = n, ncol = n) # initialise an nxn zero matrix
> for (i in 1:n) {
+   for (j in 1:n) {
+     M[i,j] <- i^(j-1) # define matrixelement
+   }
+ }
> M
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    2    4    8
[3,]    1    3    9   27
[4,]    1    4   16   64
Unlock full access  unlock