Turning an R S3 ordinary function into a generic
Asked Answered
B

1

2

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?

Bartolommeo answered 26/1, 2017 at 23:10 Comment(2)
I don't see the problem. I consider it to be a "good thing" when the help index shows you masked function help pages. Have you looked at your options under ?setMethod?Janaye
Yeah I might be asking for too much. I was hoping for a way to "merge" the base method with the new generic.Bartolommeo
Y
4

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, ])
Yah answered 27/1, 2017 at 1:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.