Exercise 1

Problem

Use the built-in data frame longley to answer the following questions.

  1. What year was the percentage of people employed relative to the population highest? Return the result as a data frame.

  2. The Korean war took place from 1950 - 1953. Filter the data frame so it only contains data from those years.

  3. What years did the number of people in the armed forces exceed the number of people unemployed? Give the result as an atomic vector.

Solution

Part 1

longley[which.max(longley$Employed / longley$Population), 
        "Year", drop=FALSE]

Part 2

longley[longley$Year %in% 1950:1953, ]

Part 3

longley$Year[longley$Armed.Forces > longley$Unemployed]
#> [1] 1951 1952 1953 1955 1956

Exercise 2

Problem

  1. Use function sloop::ftype() to see which of the following functions are S3 generics: mean, summary, print, sum, plot, View, length, [.

  2. Choose 2 of the S3 generics you identified above. How many methods exist for each? Use function sloop::s3_methods_generic().

  3. How many methods exist for classes factor and data.frame. Use function sloop::s3_methods_class().

  4. Consider a class called dollars. If a numeric vector has class dollars, function print() should print the vector with a $ in front of each number and round digits to two decimals.

Solution

Part 1

library(sloop)

Checking a couple of the functions:

ftype(mean)
#> [1] "S3"      "generic"
ftype(plot)
#> [1] "S3"      "generic"

Part 2

nrow(s3_methods_generic("mean"))
#> [1] 6
nrow(s3_methods_generic("plot"))
#> [1] 29

Part 3

nrow(s3_methods_class("factor"))
#> [1] 27
nrow(s3_methods_class("data.frame"))
#> [1] 48

Part 4

print.dollar <- function(x) {
  paste0("$", round(x, digits = 2))
}
x <- 1:5
class(x) <- "dollar"
print(x)
#> [1] "$1" "$2" "$3" "$4" "$5"
y <- c(4.292, 134.1133, 50.111)
class(y) <- "dollar"
print(y)
#> [1] "$4.29"   "$134.11" "$50.11"