[英]Generic method without class definition
如何使简单的泛型函数不变得过于复杂? 我想要这样的东西:
inputA <- function(a,b){
return(structure(c(a=a,b=b), class= "inputclassA"))
}
inputB <- function(c,d){
return(structure(c(c=c,d=d), class= "inputclassB"))
}
mathstuff.inputclassA <- function(inp){
print("inputtype: inputclassA")
inp['a'] + inp['b']
}
mathstuff.inputclassB <- function(inp){
print("inputtype: inputclassB")
inp['c'] - inp['d']
}
mystructure <- inputA(4,2)
mathstuff(mystructure) #should return 6
mystructure <- inputB(4,2)
mathstuff(mystructure) #should return 4
到目前为止,我已经这样解决了
classCheck<-function(obj,checkIs){
return (attr(obj,"class") == checkIs)
}
但是没有更好的方法吗?
好,知道了。
这是关键。 我没有意识到, “相关”线程有答案是多么可惜。
mathstuff <- function(x,...) UseMethod("mathstuff")
因此,这非常有效。 对不起这是我的错。
inputA <- function(a,b){
return(structure(c(a=a,b=b), class= "inputclassA"))
}
inputB <- function(c,d){
return(structure(c(c=c,d=d), class= "inputclassB"))
}
#make generic function
mathstuff <- function(x,...) UseMethod("mathstuff")
mathstuff.inputclassA <- function(inp){
print("inputtype: inputclassA")
inp['a'] + inp['b']
}
mathstuff.inputclassB <- function(inp){
print("inputtype: inputclassB")
inp['c'] - inp['d']
}
mystructure <- inputA(4,2)
mathstuff(mystructure)
mystructure <- inputB(4,2)
mathstuff(mystructure)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.