Exercise 1

Problem

What do each of the following return? Run the code to check your answer.

if (1 == "1") "coercion  works" else "no coercion "

ifelse(5 > c(1, 10, 2), "hello", "olleh")

Solution

if (1 == "1") "coercion  works" else "no coercion "
#> [1] "coercion  works"
ifelse(5 > c(1, 10, 2), "hello", "olleh")
#> [1] "hello" "olleh" "hello"

Exercise 2

Problem

Consider two vectors, x and y, each of length one. Write a set of conditionals that satisfy the following.

  • If x is positive and y is negative or y is positive and x is negative, print “knits”.
  • If x divided by y is positive, print “stink”.
  • Stop execution if x or y are zero.

Test your code with various x and y values. Where did you place the stop execution code?

Solution

x <- 4
y <- -10

if (x == 0 | y == 0) {
  stop("One of x or y is 0!")
} else if (x / y > 0) {
  print("stink")
} else {
  print("knits")
}
#> [1] "knits"

Exercise 3

Problem

Consider the vector x below.

x <- c(3, 4, 12, 19, 23, 49, 100, 63, 70)

Write R code that prints the perfect squares in x.

Solution

x <- c(3, 4, 12, 19, 23, 49, 100, 63, 70)

for (i in x) {
  if (sqrt(i) %% 1) {
    next
  }
  print(i)
}
#> [1] 4
#> [1] 49
#> [1] 100

Exercise 4

Problem

Consider z <- c(-1, .5, 0, .5, 1). Write R code that prints the smallest non-negative integer \(k\) satisfying the inequality \[\lvert cos(k) - z \rvert < 0.001\] for each component of z.

Solution

for (z in c(-1, .5, 0, .5, 1)) {
  k <- 0
  while (abs(cos(k) - z) >= .001) {
    k <- k + 1
  }
  print(k)
}
#> [1] 22
#> [1] 21766
#> [1] 40459
#> [1] 21766
#> [1] 0

Exercise 5

Problem

One way to time your code in R is with system.time(). For example,

system.time({
  Sys.sleep(3) # suspend code execution for 3 seconds
  runif(n = 1) # generate one uniform(0, 1) random variable
})
#>    user  system elapsed 
#>   0.000   0.000   3.003

calculates the elapsed time to be a little over three seconds. Most of the elapsed time was due to Sys.sleep(). We’ll discuss the user and system times later in the course.

To quantify the inefficiency of a poorly written for loop, time both the code blocks below. Experiment with different values of n. What do you observe?

n <- 10
x <- 1
for (i in seq_len(n)) {
  x <- c(x, sqrt(x[i] * i))
}
n <- 10
x <- rep(1, n + 1)
for (i in seq_len(n)) {
  x[i + 1] <- sqrt(x[i] * i)
}

Solution

Loop expression 1:

system.time({
  n <- 100000
  x <- 1
  for (i in seq_len(n)) {
    x <- c(x, sqrt(x[i] * i))
  }
})
#>    user  system elapsed 
#>  15.051   8.471  23.669

Loop expression 2:

system.time({
  n <- 100000
  x <- rep(1, n + 1)
  for (i in seq_len(n)) {
    x[i + 1] <- sqrt(x[i] * i)
  }
})
#>    user  system elapsed 
#>   0.011   0.000   0.012