Appendix D. Solutions to Exercises

Exercise 1-1
If you get stuck, ask your system administrator, or ask on the R-help mailing list.
Exercise 1-2
Use the colon operator to create a vector, and the sd function:
sd(0:100)
Exercise 1-3
Type demo(plotmath) and hit Enter, or click the plots to see what’s on offer.
Exercise 2-1
  1. Simple division gets the reciprocal, and atan calculates the inverse (arc) tangent:

    atan(1 / 1:1000)
  2. Assign variables using <-:

    x <- 1:1000
    y <- atan(1 / x)
    z <- 1 / tan(y)
Exercise 2-2
For comparing two vectors that should contain the same numbers, all.equal is usually what you need:
x == z
identical(x, z)
all.equal(x, z)
all.equal(x, z, tolerance = 0)
Exercise 2-3
The exact values contained in the following three vectors may vary:
true_and_missing <- c(NA, TRUE, NA)
false_and_missing <- c(FALSE, FALSE, NA)
mixed <- c(TRUE, FALSE, NA)

any(true_and_missing)
any(false_and_missing)
any(mixed)
all(true_and_missing)
all(false_and_missing)
all(mixed)
Exercise 3-1
class(Inf)
class(NA)
class(NaN)
class("")

Repeat with typeof, mode, and storage.mode.

Exercise 3-2
pets <- factor(sample(
  c("dog", "cat", "hamster", "goldfish"),
  1000,
  replace = TRUE
))
head(pets)
summary(pets)

Converting to factors is recommended but not compulsory.

Exercise 3-3
carrot <- 1
potato <- 2
swede  <- 3
ls(pattern = "a")

Your vegetables may vary.

Exercise 4-1
There are several possibilities for creating sequences, including the colon operator. This solution uses seq_len and seq_along:
n <- ...

Get Learning R now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.