Learning Objectives

Motivation

If-statements

For-loops

Advanced R Exercises

  1. Why does this code succeed without errors or warnings?

    x <- numeric()
    out <- vector("list", length(x))
    for (i in 1:length(x)) {
      out[i] <- x[i] ^ 2
    }
    out
    ## [[1]]
    ## [1] NA
  2. Why doesn’t this for-loop go on forever?

    xs <- c(1, 2, 3)
    for (x in xs) {
      xs <- c(xs, x * 2)
    }
    xs
    ## [1] 1 2 3 2 4 6
  3. What does the following code tell you about when the index is updated?

    for (i in 1:3) {
      i <- i * 2
      print(i) 
    }
    ## [1] 2
    ## [1] 4
    ## [1] 6

National Science Foundation Logo American University Logo Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.