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.

x=0
for (i in 1:3) { 
                x=x+i
                print(x)
                }
## [1] 1
## [1] 3
## [1] 6

We can also use it to study the behavior of the arithmetic mean

out = rep(0,100)
n = 20
for (i in 1:100) { 
                x = rnorm(n, mean = 0,sd = 1)
                out[i]=mean(x)
}
mean(out)
## [1] 0.005656675
sd(out)
## [1] 0.2231626
out = rep(0,100)
n = 200
for (i in 1:100) { 
                x = rnorm(n,mean = 0,sd = 1)
                out[i]=mean(x)
}
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###
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.

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.

i <- 1

while (i < 6) {
   print(i)
   i = i+1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5