Chapter 4 Simple programming
Very often we want to repeat a particular operation many times: either over different elements of a given data structure (columns of a matrix, individual elements of a vector), or perform an operation until a satisfactory result is reached (run an algorithm until the value converges to a prespecified level). As well, we sometimes have to check whether a condition about the data is fulfilled, e.g. are elements of a vector equal to 0 and perform different operations depending on the result.
4.1 Using for-loops
A for-loop is a procedure in which a particular routine is repeated and only an index variable is changed.
## [1] 1
## [1] 3
## [1] 6
We can also use it to study the behavior of the arithmetic mean
## [1] 0.005656675
## [1] 0.2231626
## [1] -0.004593488
## [1] 0.06389977
4.2 The if-Condition
Within a for-loop, it may be useful to perform arithmetic operations only under certain conditions. The basic syntax for this is
where else can remain unspecified.
###If-condition###
y<-c(1,4,5,2,7,8,2,4)
N <- length(y)
1:N
##
y.sq <- numeric(N)#creates an empty numeric vector of length N
for(i in 1:N){ #initializing the for-loop
y.sq[i] <- y[i]^2#every element of y.sq is replaced by the respective squared value.
if(i == N){#only when this condition is met, i.e. in the last iteration of the loop
print(y.sq)#is the vector printed
}
}
In shorter form the ifelse() command is an alternative.
4.3 The while-loop
The while-loop performs a program (“statement”) as long as certain data conditions (“test expression”) are met. The basic syntax is
Here, test_expression is evaluated and the body of the loop is entered if the result is TRUE.
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5