问题
FYI, looks like this question already has a LISP equivalent.
Recently I wanted to create a dataframe extension to the R base function setdiff
and thought a generic would be nice. The following works but is clunky:
#' @export setdiff.default
setdiff.default <- setdiff
#' @export
setdiff <- function(x, ...) {
UseMethod("setdiff")
}
#' @export
setdiff.data.frame <- function(A, B) {
A[!duplicated(rbind(B, A))[nrow(B) + 1:nrow(A)], ]
}
When you load the package, the base function is masked. If I write extra documentation for the new function, an other .Rd file is created and competes with the original base R function (R asks you to choose which one you want when you run ?setdiff
).
Is there a clean way to do this?
回答1:
It can be done using S4. Note that setdiff
uses x and y as arguments so the method should too:
setGeneric("setdiff")
setdiff.data.frame <- function(x, y) {
x[!duplicated(rbind(y, x))[nrow(y) + 1:nrow(x)], ]
}
setMethod("setdiff", signature("data.frame", "data.frame"), setdiff.data.frame)
# test
setdiff(BOD[1:3, ], BOD[2:4, ])
来源:https://stackoverflow.com/questions/41884629/turning-an-r-s3-ordinary-function-into-a-generic