R中的S3类的方法调度:多个更高类的特定子类的指定方法
问题描述:
我正在研究脚本的集合,并使用s3类和方法来使事情保持一点清洁。R中的S3类的方法调度:多个更高类的特定子类的指定方法
该类结构有三个级别。
- 级别1:data.frame
- 级别2:sample_report OR 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_report
和foo.fix_report
尸体做什么是你希望他们做的。对象的类被分配为c("stim_report","sub_class", "data.frame")
而不仅仅是c("stim_report","sub_class")
,以便它们可以继承其他S3泛型,如nrow
。
谢谢!奇迹般有效。 – jwdink 2014-08-30 18:15:25