Control Structures

Commonly used control structures are:

Conditional statements with if-else

if(<condition>) {
        ## do something
} 
## Continue with rest of code
if(<condition>) {
        ## do something
} 
else {
        ## do something else
}
if(<condition1>) {
        ## do something
} else if(<condition2>)  {
        ## do something different
} else {
        ## do something different
}
## Generate a uniform random number
x <- runif(1, 0, 10)  

x
## [1] 3.386759
if(x > 3) {
        y <- 10
} else {
        y <- 0
}

y
## [1] 10

Important Operators

Comparison operators:

Logical operators:

for Loops

for(i in 1:5) {
  print (i)
  }
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
x <- c("a", "b", "c", "d")

for(i in 1:4) {
        ## Print out each element of 'x'
        print(x[i])  
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
## Generate a sequence based on length of 'x'
for(i in seq_along(x)) {   
        print(x[i])
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
for(letter in x) {
        print(letter)
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
for(i in 1:4) print(x[i])
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"

Nested for Loops

x <- matrix(1:6, 2, 3)
for(i in seq_len(nrow(x))) {
        for(j in seq_len(ncol(x))) {
                print(x[i, j])
        }   
}
## [1] 1
## [1] 3
## [1] 5
## [1] 2
## [1] 4
## [1] 6

while Loops

count <- 0
while(count < 10) {
        print(count)
        count <- count + 1
}
## [1] 0
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
z <- 5
set.seed(1)
while(z >= 3 && z <= 10) {
        coin <- rbinom(1, 1, 0.5)
        
        if(coin == 1) {  ## random walk
                z <- z + 1
        } else {
                z <- z - 1
        } 
}
print(z)
## [1] 2

Functions

Here’s a simple function that takes no arguments and does nothing.

f <- function() {
         ## This is an empty function
}

class(f)
## [1] "function"
f()
## NULL

Now let’s create a function that actually has a function body

f <- function() {
  cat("Hello, world!\n")
}

f()
## Hello, world!
f <- function(num) {
        for(i in seq_len(num)) {
                cat("Hello, world!\n")
        }
}

f(3)
## Hello, world!
## Hello, world!
## Hello, world!
f <- function(num) {
        hello <- "Hello, world!\n"
        for(i in seq_len(num)) {
               cat(hello)
        }
        chars <- nchar(hello) * num
        chars
}
meaningoflife <- f(3)
## Hello, world!
## Hello, world!
## Hello, world!
print(meaningoflife)
## [1] 42
f()
f <- function(num = 1) {
        hello <- "Hello, world!\n"
        for(i in seq_len(num)) {
                cat(hello)
        }
        chars <- nchar(hello) * num
        chars
}

f()    ## Use default value for 'num'
## Hello, world!
## [1] 14
f(2)   ## Use user-specified value
## Hello, world!
## Hello, world!
## [1] 28
f(num = 2)
## Hello, world!
## Hello, world!
## [1] 28