R for modellers - Vignette 05

Flow control

Julien Arino

Department of Mathematics

University of Manitoba*




* The University of Manitoba campuses are located on original lands of Anishinaabeg, Cree, Oji-Cree, Dakota and Dene peoples, and on the homeland of the Métis Nation.

for loops

for applies to lists or vectors


for (i in 1:10) {
  something using integer i
}
for (j in c(1,3,4)) {
  something using integer j
}
for (n in c("truc", "muche", "chose")) {
  something using string n
}
for (m in list("truc", "muche", "chose", 1, 2)) {
  something using string n or integer n, depending
}
for (i in c(1:3, 5, 10)) {
  writeLines(paste0("i=",i,", i*2=",i*2))
}
i=1, i*2=2
i=2, i*2=4
i=3, i*2=6
i=5, i*2=10
i=10, i*2=20


for (i in c(1:3, 5, 10)) {
  ch = sprintf("i=%d, i*3=%d", i, i*3)
  print(ch)
}
[1] "i=1, i*3=3"
[1] "i=2, i*3=6"
[1] "i=3, i*3=9"
[1] "i=5, i*3=15"
[1] "i=10, i*3=30"
for (i in c("truc", "muche", "chose")) {
  writeLines(paste0("i=",i))
}
i=truc
i=muche
i=chose


for (i in c("truc", "muche", "chose", 1, 22)) {
  writeLines(paste0("is.character(i)=",
                    is.character(i)))
}
is.character(i)=TRUE
is.character(i)=TRUE
is.character(i)=TRUE
is.character(i)=TRUE
is.character(i)=TRUE
is.character(c(1, 22))
[1] FALSE

while loops

repeat loops

if statements

if (condition is true) {
  list of stuff to do
}

Even if list of stuff to do is a single instruction, better to use curly braces


if (condition is true) {
  list of stuff to do
} else if (another condition) {
  ...
} else {
  ...
}

ifelse statements


Very useful to set values based on simple tests


ifelse(condition, value-when-true, value-when-false)


a = 5
b = ifelse(a < 10, 1, 2)
c = ifelse(a > 10, 1, 2)
writeLines(paste0("b=", b, ", c=", c))
b=1, c=2

break statement

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop

for (i in 1:5) {
  if (i == 3) {
    writeLines('i==3, quitting')
    break
  }
  writeLines(paste0('i=', i))
}
i=1
i=2
i==3, quitting

next statement

next halts the processing of the current iteration and advances the looping index

for (i in 1:5) {
  if (i == 3) {
    writeLines('i==3, skipping ahead')
    next
  }
  writeLines(paste0('i=', i))
}
i=1
i=2
i==3, skipping ahead
i=4
i=5

Important remark

Both break and next apply only to the innermost of nested loops

for (i in 1:3) {
  for (j in 1:3) {
    if (j == 2) {
      writeLines('j==2, quitting')
      break
    }
    writeLines(paste0('i=', i, ", j=", j))
  }
}
i=1, j=1
j==2, quitting
i=2, j=1
j==2, quitting
i=3, j=1
j==2, quitting
for (i in 1:3) {
  for (j in 1:3) {
    if (j == 2) {
      writeLines('j==2, skipping ahead')
      next
    }
    writeLines(paste0('i=', i, ", j=", j))
  }
}
i=1, j=1
j==2, skipping ahead
i=1, j=3
i=2, j=1
j==2, skipping ahead
i=2, j=3
i=3, j=1
j==2, skipping ahead
i=3, j=3