我已經創建了幾個S3方法,我通過在對象上設置類來進行控制。事情是這樣的:結合S3方法
myfun <- function (x) {
UseMethod("myfun")
}
myfun.a <- function(x) {
print("Type a")
}
myfun.b <- function(x) {
print("Type b")
}
myfun.c <- function(x) {
print("Type c")
}
myfun(structure(c(1:3), class = "a"))
# [1] "Type a"
myfun(structure(c(1:3), class = "b"))
# [1] "Type b"
myfun(structure(c(1:3), class = "c"))
# [1] "Type c"
有時候,這些類的某個子集能夠共享的方法是這樣的:
otherfun <- function (x) {
UseMethod("otherfun")
}
otherfun.a <- function(x) {
print("Type a")
}
otherfun.b <- function(x) { ## Doesn't work because its only called for "b"
print("Type b or c")
}
otherfun(structure(c(1:3), class = "a"))
# [1] "Type a"
otherfun(structure(c(1:3), class = "b"))
# [1] "Type b or c"
otherfun(structure(c(1:3), class = "c"))
# [1] "Type b or c"
什麼是實現多個類型共用一個最好的/最正確的方法方法?我不想在對象上堆疊類,因爲類「b」和「c」在大多數方面都不相同。
我正在考慮使用默認的方法和手動解析類的類型,是這樣的:
otherfun <- function (x) {
UseMethod("otherfun")
}
otherfun.a <- function(x) {
print("Type a")
}
otherfun.b <- function(x) {
print("Type b or c")
}
otherfun.default <- function(x) {
if(class(x) == "c") otherfun.b(x)
else stop("Bad Class on x")
}
otherfun(structure(c(1:3), class = "a"))
# [1] "Type a"
otherfun(structure(c(1:3), class = "b"))
# [1] "Type b or c"
otherfun(structure(c(1:3), class = "c"))
# [1] "Type b or c"
我喜歡這一點,謝謝...明天我會接受它作爲答案。 –