Control Structures

R has the standard control structures you would expect. expr can be multiple (compound) statements by enclosing them in braces { }. It is more efficient to use built-in functions rather than control structures whenever possible.

if-else

if (cond) expr
if (cond) expr1 else expr2

for

for (var in seq) expr

while

while (cond) expr

switch

switch(expr, ...)

ifelse

ifelse(test,yes,no)

Example

# transpose of a matrix
# a poor alternative to built-in t() function

mytrans <- function(x) {
  if (!is.matrix(x)) {
    warning("argument is not a matrix: returning NA")
    return(NA_real_)
  }
  y <- matrix(1, nrow=ncol(x), ncol=nrow(x))
  for (i in 1:nrow(x)) {
    for (j in 1:ncol(x)) {
      y[j,i] <- x[i,j]
    }
  }
  return(y)
}

# try it
z <- matrix(1:10, nrow=5, ncol=2)
tz <- mytrans(z)

Going Further

To practice working with control structures in R, try the chapter on conditionals and control flow of this interactive R course.