2

I have been trying to develop my S3 learnings. Have I used object correctly here? I want to create a summary and print and plot classes. I'm using a t-test for the moment but the function itself is not important - getting the S3 code right is.

Note: I've read everything i can find and recommended - but as they keep using sloop or lm I'm just not understanding what is unique or what is contained in those packages - i want to build from scratch. Thank you

library(gapminder)
library(dplyr)
library(ggplot2)

head(gapminder)
str(gapminder)

part3 <- gapminder
Asia1 <- subset(part3, continent == "Asia")
Africa1 <- subset(part3, continent =="Africa")
part3c <- rbind(Asia1, Africa1)

summary.part3s3b <-function(part3g) {
  cat('The following should give t-test results:\n')
  part3g <- t.test(data = part3c,
                   lifeExp ~ continent)
  part3g
}
summary(part3g)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
ceallac
  • 107
  • 9
  • I think you’re misunderstanding the point of the ‘sloop’ package: it is used in *Advanced R* purely as an investigative tool, to help explaining S3. It isn’t used to *write code* with S3. – Konrad Rudolph Jan 05 '22 at 13:41

1 Answers1

3

We define a constructor to create part3s3b objects and a summary and plot method. The summary method creates an object of class summary.part3s3b and it has a print method. Then we test it out. Look at lm, print.lm, plot.lm, summary.lm, print.summary.lm for another example.

# construct a part3s3b object
part3s3b <- function(x, ...) {
  structure(x, class = c("part3s3b", setdiff(class(x), "part3s3b")))
}

# construct summary.part3s3b object which is an htest with 
#  a c("summary.part3s3b", "htest") class
summary.part3s3b <- function(object, ...) {
  y <- t.test(data = object, lifeExp ~ continent)
  structure(y, class = c("summary.part3s3b", "htest"))
}

# same as print.htest except it also displays a line at the beginning
print.summary.part3s3b <-function(x, ...) {
  cat('The following should give t-test results:\n')
  NextMethod()
}

plot.part3s3b <- function(x, ...) {
  cat("plotting...\n")
  NextMethod()
}

# test    
X <- part3s3b(part3c)  # create part3s3b object X
summary(X)  # run summary.part3s3b and print.summary.part3s3b
plot(X)  # run plot.part3s3b
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Is `plot.part3s3b` necessary? Since it just dispatches to the “parent class” method, omitting it should have the same effect. – Konrad Rudolph Jan 05 '22 at 13:40
  • 1
    It is not necessary here but the question indicated that the specific functionality is not of concern. I will add a cat to it so it is not identical just to be clear. – G. Grothendieck Jan 05 '22 at 13:41
  • @KonradRudolph thank you!! I'm going to try to get to grips with this! ```NextMethod()``` is a new one for me and I'm going to look on SO for information on how to understand it! – ceallac Jan 05 '22 at 16:33