R control structures | Easy

Control structures in R allow you to control the flow of execution of the program, depending on runtime conditions.

Common structures are:

  • if, else: testing a condition
  • for: execute a loop a fixed number of times
  • while: execute a loop while a condition is true
  • repeat: execute an infinite loop
  • break: break the execution of a loop
  • next: skip an interaction of a loop
  • return: exit a function

Most control structures are not used in interactive sessions, but rather when writing functions or longer expressions.

if else

Example: Single if, else

if (TRUE) { 
    # if
}else{
    # else
}

Example: Multiple if, else

if (TRUE) { 
    # if
} else if{
    # elseif
} else{
    # else
}

for

Example: for loop

for(i in 1:100) { 
print (i) 
}

Example: for loop in c()

for(i in c('we', 'are', 'here')){
    print(i)
} 

Out:

[1] "we"
[1] "are"
[1] "here"

c() combine values into a vector or List

c() seams to be one of the most frequent functions in R and means combine.

while

Example: while(){}

set.seed(123)
z<-5 
while(z>=3 && z<=10) { 
  print (z) 
  coin <- rbinom(1, 1, 0.5)
  if (coin == 1) { ## coin head
    z<-z+1
  }else { 
    z<-z-1
  }
}

If you asked your self what is rbinom(1, 1, 0.5) -> this is a coin tossing random variable. It will always produce either 0 or 1 as results.

repeat and break

You will probable not need repeat and model it simple with the for loop, but for the demonstration:

Example: repeat{}

z<-10
repeat{
  print(z)
  z<-z-1
  if (z==0)  break
}

Output:

[1] 10
[1] 9
[1] 8
[1] 7
[1] 6
[1] 5
[1] 4
[1] 3
[1] 2
[1] 1

break is used to escape the loop made with for, repeat or while.

next

To check what next() can do:

Example: next()

z<-10
repeat{
  print(z)
  if (z==5){
    z<-z-2
    next
  }
  z<-z-1
  if (z==0)  break
}

Out:

[1] 10
[1] 9
[1] 8
[1] 7
[1] 6
[1] 5
[1] 3
[1] 2
[1] 1

return

In R function is something that can have zero or more returns.

check_sign_status <- function(x) {
    if (x > 0) {
        result <- "Positive"
    }else if (x < 0) {
        result <- "Negative"
    }else {
        result <- "Zero"
    }
    return(result)
}

Without a problem we can still rewrite this function:

check_sign_status <- function(x) {
    if (x > 0) {
        result <- "Positive"
    }else if (x < 0) {
        result <- "Negative"
    }else {
        result <- "Zero"
    }
    result
}

It will work just the same as the first case, but no explicit return in the second case.

I would always advice to avoid code without the return.

Finally here is something with more than one return.

check_sign_status <- function(x) {
  if (x > 0) {
    return("Positive")
  }else if (x < 0) {
    return("Negative")
  }else {
    return("Zero")
  }
  return('Never gets in here')
}

We call the function simple as:

check_sign_status(53)

tags: control structures & category: r