Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中S3类的方法分派:为多个更高类的特定子类指定方法_R_Class_Methods_R S3 - Fatal编程技术网

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

R中S3类的方法分派:为多个更高类的特定子类指定方法,r,class,methods,r-s3,R,Class,Methods,R S3,我正在编写一个脚本集合,并使用s3类和方法来保持事情的整洁 班级结构有三个层次 级别1:data.frame 第2级:样本报告或修复报告 第3级:刺激报告 我想写一个函数,它只获取类stim_report的数据帧,然后根据stim_report是从sample_report继承还是从fix_report继承来分派不同的方法 显然,我可以做一些类似的事情 myfunction.stim_report(df) if ("sample_report" %in% class(df)) { % do

我正在编写一个脚本集合,并使用s3类和方法来保持事情的整洁

班级结构有三个层次

  • 级别1:data.frame
  • 第2级:样本报告或修复报告
  • 第3级:刺激报告
我想写一个函数,它只获取类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"

Df1谢谢!工作起来很有魅力。