Turning an R S3 ordinary function into a generic

北城余情 提交于 2020-01-21 09:10:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!