Skip to Content
Learning R
book

Learning R

by Richard Cotton
September 2013
Beginner to intermediate
396 pages
8h 8m
English
O'Reilly Media, Inc.
Content preview from Learning R

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 <- ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced R

Advanced R

Hadley Wickham
The R Book

The R Book

Michael J. Crawley
The R Book, 2nd Edition

The R Book, 2nd Edition

Michael J. Crawley

Publisher Resources

ISBN: 9781449357160Errata PageSupplemental Content