Week 2

if(<condition>) {
    ## do something
} {
    ## do something else
}
if(<condition1>) {
    ## do something
} else if(<condition2>) {
    ## do something different
} else {
    ## do something different
}
This is a valid if/else structure
x <- 5
if(x>3) {          ## If x is greater than 3
      y <- 10      ## Then we select y is equal to 10
} else {           ## else
      y <- 0       ## y is 0
}

## So is this one, same as above.  If x>3, 10, if not 0.
y <- if(x>3) {
        10
} else {
        0
}
For Loops
for(i in 1:10) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
## This loop takes the i variable and in each iteration of the loop gives it values 1, 2, 3, 4,...,10, then exits.
Consider:
x <- c("a", "b", "c", "d")
for(i in 1:4) {
  print(x[i])
}
## [1] "a"
## [1] "b"
## [1] "c"
## [1] "d"
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 (loop while condition is true)
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
while(z >= 3 && z <=10) {
  print(z)
  coin <- rbinom(1,1,0.5)
  if(coin == 1) {
    z <- z + 1
  } else {
    z <- z - 1
  }
}
## [1] 5
## [1] 4
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 8
## [1] 7
## [1] 6
## [1] 7
## [1] 6
## [1] 5
## [1] 6
## [1] 7
## [1] 6
## [1] 5
## [1] 6
## [1] 5
## [1] 4
## [1] 5
## [1] 6
## [1] 5
## [1] 6
## [1] 5
## [1] 6
## [1] 5
## [1] 4
## [1] 3