Exercise 1

Problem

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

  1. Which 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. Which 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 accounting. If a numeric vector has this class, function print() should print the vector with a $ in front of each number and display values up to two decimals. Create a method for this class.

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] 49

Part 4

print.accounting <- function(x) {
  print(paste0("$", format(round(x, digits = 2), nsmall = 2)), quote = FALSE)
}
x <- 1:5
class(x) <- "accounting"
print(x)
#> [1] $1.00 $2.00 $3.00 $4.00 $5.00
y <- c(4.292, 134.1133, 50.111)
class(y) <- "accounting"
print(y)
#> [1] $  4.29 $134.11 $ 50.11