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)
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