Arman Akbarian
UNIVERSITY OF BRITISH COLUMBIA
PHYSICS & ASTRONOMY DEPT.

#----------------------------------
# AAK: Mon 10 Aug 2014 00:10:58 PDT
# Control structure in R
#-----------------------------------

x <- 5
# If statement:
if (x < 1) {
  y <- 0
} else if (x < 3)  {
  y <- 0.5
} else {
  y <- 1
}

cat("Value of y is:",y,"\n")

# Another form of if statement:
y <- if (x < 1){
  1
} else {
  0
}

cat("Value of y is:",y,"\n")

x<- c('a','b','c','d')

# For loop:
cat("First type of for loop:\n")
for (i in 1:4) {
    print(x[i])
}

cat("Second type of for loop:\n")
for (i in seq_along(x)){
  print(x[i])
}

cat("Third type of for loop:\n")
for (l in x) {
  print(l)
}

M <- matrix(1:6,2,3)
# Nested for loop:
for (i in 1:nrow(M)) {
 for (j in 1:ncol(M)) {
   cat("M(",i,",",j,")=",M[i,j],"  ")
 }
   cat("\n")
}

# While loop, and next

count <- 0
y <- 0
while (count < 10) {
  count <- count + 1
  if (count == 7) { #Skips 7 
    next
  }
  y <- c(y, count^2)
}
print(y)


last update: Wed Aug 19, 2015