繁体   English   中英

R中为S3类分配的方法:为多个更高类的特定子类指定方法

[英]Methods dispatch for S3 classes in R: specifying method for particular subclass of multiple higher classes

我正在研究脚本的集合,并使用s3类和方法使事情更简洁。

类结构具有三个级别。

  • 级别1:data.frame
  • 级别2:sample_report或fix_report
  • 第3级:stim_report

我想编写一个仅接受stim_report类的数据帧,然后根据stim_report是从sample_report继承还是从fix_report继承的方法,分配一个不同的方法。

显然,我可以做类似的事情

myfunction.stim_report(df)

if ("sample_report" %in% class(df)) {
% do something 
} else if ("fix_report" %in% class(df)) {
% do something 
}

但这破坏了方法分派的目的。

请注意,我需要做一些事情,以便在数据框的类不是stim_report时函数将返回错误。 所以我想我也可以做:

myfunction.fix_report(df)
if ("stim_report" %in% class(df)) {
% do something 
} else {
stop("No method found")
}

myfunction.sample_report(df)
if ("stim_report" %in% class(df)) {
% do something 
} else {
stop("No method found")
}

但是再次,这感觉像是违反了S3方法的全部观点。

有正确的方法吗?

那这样的事情呢-

Df1 <- data.frame(
  x = 1:5,
  y = rexp(5))
##
Df2 <- data.frame(
  x = 6:10,
  y = rexp(5))
##
Df3 <- data.frame(
  x = 11:15,
  y = rexp(5))
##
class(Df1) <- c("stim_report","sample_report","data.frame")
class(Df2) <- c("stim_report","fix_report", "data.frame")
##
foo <- function(x){
  UseMethod("foo",x)
}
foo.sample_report <- function(x){
  x[sample(1:nrow(x),3),]
}
foo.fix_report <- function(x){
  x[,2] <- cumsum(x[,2])
  x
}
##
> foo(Df1)
  x         y
3 3 0.9400994
5 5 0.3708902
1 1 0.7521028
> foo(Df2)
   x        y
1  6 2.408421
2  7 2.637971
3  8 3.465672
4  9 3.571835
5 10 5.468710
> foo(Df3)
Error in UseMethod("foo", x) : 
  no applicable method for 'foo' applied to an object of class "data.frame"

您将在其中更改foo.sample_reportfoo.fix_report以执行您希望它们执行的任何操作。 对象的类被分配为c("stim_report","sub_class", "data.frame")而不是c("stim_report","sub_class")以便它们可以继承其他S3泛型,例如nrow

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM