What does 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")
if (1 == "1") "coercion works" else "no coercion "
#> [1] "coercion works"
ifelse(5 > c(1, 10, 2), "hello", "olleh")
#> [1] "hello" "olleh" "hello"
Consider two vectors, x
and y
, each of length one. Write a set of conditionals that satisfy the following.
x
is positive and y
is negative or y
is positive and x
is negative, print “knits”.x
divided by y
is positive, print “stink”.x
or y
are zero.Test your code with various x
and y
values. Where did you place the stop execution code?
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"
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
.
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
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
.
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
One way to time your code in R is with system.time()
. For example,
system.time({
Sys.sleep(3) # sleep system for 3 seconds
runif(n = 1) # generate one uniform(0, 1) random variable
})
#> user system elapsed
#> 0.000 0.000 3.001
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)
}
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
#> 17.042 10.398 27.930
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.014 0.001 0.014