简体   繁体   中英

Turning an R S3 ordinary function into a generic

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?

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, ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM