9 Loops and ifelse statements

9.1 Loops

In programming loops are very common and represent the most basic way to accomplish tasks recursively and or repetitively. We will learn about other ways to handle repetitive operations, but loops are still widely used.

Structure of loops:

for (i in 1:5) # Run the loop by single integers
{              # start loop
  # run recursive calculation here
}              # end loop
for (i in 1:5) 
{
  print(i)
}
n <- 4
for(i in 1:n) 
{
  print("Hello World")
}
n <- 8
n.vect <- c()
for(i in 1:n) 
{
  n.vect[i] <- i + 2
  print(n.vect)
}

Practice

# Use a loop to calculate: 1/2 + 2/3 + 3/4 + 4/5

9.2 Nested Loops

# for (variable in sequence) {
#   for (variable in sequence) {
#     expression 
#   } 
# }

# Example:
# for(i in 1:n) {
#   for(j in 1:n) {
#     expression
#   }
# }
for (k in 1:3) {
  for (l in 1:2) {
    print(paste("k =", k, "l= ",l))
  }
}
res = matrix(nrow=4, ncol=4) # create a 4 x 4 matrix (of 4 rows and 4 columns)
for(i in 1:nrow(res)) {   # Assigned a variable  ‘i’for each row
  for(j in 1:ncol(res)) { # Assigned a variable  ‘j for each column
    res[i,j] = i*j        # calculating product of two indices
  }
}
print(res)

9.3 while loop

Syntax of while loop: while (test_expression) { statement }

i <- 1
while (i < 6) {
print(i)
i = i+1
}

9.4 If, else, and ifelse

If statements are useful if we want R to do something based on our logical question.

a <- 7
if (a == 7) print("a is 7")

If the condition is not met, nothing will print to the console

a <- 7
if (a == 5) print("a is 7")

The same approach works if we want to use not logical.

a <- 7
if (a != 5) print("a is not 5")

Using if and else together allows you to do one thing if the condition is true and something else if the condition is false.

a <- 7
if (a == 7) print("a is 7") else print("a is not 7")
a <- 8
if (a == 7) print("a is 7") else print("a is not 7")

The if and else function only can assess one element at a time. To assess a whole vector, you can use the ifelse function

a.vec <- c(4,3,6,7)
ifelse(a.vec > 5, "Greater", "Less Than")

Create this data frame in R representing the maximum observed tidal amplitude each year (Fictional Data). In years from 1990 to 1992, tide was measured in centimeters, from 1993 to 1995 it was measured in milimeters.

tide.df <- data.frame(Year = c(1990:1995), height = c(130, 230, 210, 1450, 1870, 2200 ))
  • Use ifelse statements to first print to screen whether each row is “pre-change” or “post-change”
  • Next use ifelse to create a new variable with the tidal amplitude in meters
tide.df <- data.frame(Year = c(1990:1995), height = c(13, 23, 21, 14, 18, 22))
ifelse(tide.df$Year <= 1992,"Pre-change", "Post-Change")
tide.df$height <- ifelse(tide.df$Year <= 1992, 
                         tide.df$height/100, 
                         tide.df$height/1000)