簡體   English   中英

S3 object 如何調用方法?

[英]How does an S3 object invoke a method?

我一直在努力發展我的 S3 學習。 我在這里正確使用object嗎? 我想創建一個summaryprintplot類。 我目前正在使用 t 檢驗,但 function 本身並不重要 - 正確獲取 S3 代碼才是。

注意:我已經閱讀了我能找到並推薦的所有內容 - 但由於他們一直在使用 sloop 或 lm,我只是不了解這些包中的獨特之處或包含的內容 - 我想從頭開始構建。 謝謝

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)

我們定義了一個構造函數來創建 part3s3b 對象和一個摘要和 plot 方法。 summary 方法創建 class summary.part3s3b 的 object 並且它具有打印方法。 然后我們測試一下。 查看 lm、print.lm、plot.lm、summary.lm、print.summary.lm 的另一個示例。

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM