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.
0
x=for (i in 1:3) {
+i
x=xprint(x)
}
## [1] 1
## [1] 3
## [1] 6
We can also use it to study the behavior of the arithmetic mean
rep(0,100)
out = 20
n =for (i in 1:100) {
rnorm(n, mean = 0,sd = 1)
x =mean(x)
out[i]=
}mean(out)
## [1] 0.005656675
sd(out)
## [1] 0.2231626
rep(0,100)
out = 200
n =for (i in 1:100) {
rnorm(n,mean = 0,sd = 1)
x =mean(x)
out[i]=
}mean(out)
## [1] -0.004593488
sd(out)
## [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
if (condition){
statement
} else{
alternative }
where else can remain unspecified.
###If-condition###
c(1,4,5,2,7,8,2,4)
y<- length(y)
N <-1:N
##
numeric(N)#creates an empty numeric vector of length N
y.sq <-
for(i in 1:N){ #initializing the for-loop
y[i]^2#every element of y.sq is replaced by the respective squared value.
y.sq[i] <-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.
ifelse(test, yes, no)
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
while (testexpression)
{#increment (i+1);
statement }
Here, test_expression is evaluated and the body of the loop is entered if the result is TRUE.
1
i <-
while (i < 6) {
print(i)
i+1
i = }
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5