7 Control Structures, Looping, and Applying

7.1 Control Structures and Looping

7.1.1 Control Structures in R

  • R has multiple types of control structures that allows for sequential evaluation of statements.

  • For loops

    for (x in set) {operations}
  • while loops

    while (x in condition){operations}
  • If statements (conditional)

    if (condition) {
    some operations 
     } else { other operations }

7.1.2 Control Structure and Looping Examples

x<-1:9
length(x)
# a simple conditional then two expressions
if (length(x)<=10) {
   x<-c(x,10:20);print(x)}
# more complex 
if (length(x)<5) {
    print(x)
} else {
    print(x[5:20])
}           
# print the values of x, one at a time
for (i in x) print(i) 
for(i in x) i   # note R will not echo in a loop

7.1.3 Control Structure and Looping Examples

# loop over a character vector
y<-c('a','b','hi there')            
for (i in y) print(i)

# and a while loop
j<-1                
while(j<10) { # do this while j<10      
  print(j)
  j<-j+2} # at each iteration, increase j by 2

7.2 Applying

7.2.1 Why Does R Have Apply Functions

  • Often we want to apply the same function to all the rows or columns of a matrix, or all the elements of a list.

  • We could do this in a loop, but loops take a lot of time in an interpreted language like R.

  • R has more efficient built-in operators, the apply functions.

example If mat is a matrix and fun is a function (such as mean, var, lm …) that takes a vector as its argument, then you can:

apply(mat,1,fun) # over rows--second argument is 1      
apply(mat,2,fun) # over columns--second argument is 2

In either case, the output is a vector.

7.2.2 Apply Function Exercise

  1. Using the matrix and rnorm functions, create a matrix with 20 rows and 10 columns (200 values total) of random normal deviates.

  2. Compute the mean for each row of the matrix.

  3. Compute the median for each column.