将R S3普通函数转换为通用函数 [英] Turning an R S3 ordinary function into a generic
问题描述
最近我想为R base函数 setdiff
创建一个数据框扩展,并且认为泛型会对人好点。以下工作,但很笨重:
#'@export setdiff.default
setdiff.default< - setdiff
#'@export
setdiff< - function(x,...){
UseMethod(setdiff)
}
#'@导出
setdiff.data.frame< - 函数(A,B){
A [!duplicated(rbind(B,A))[nrow(B)+ 1:nrow(A)], ]
}
加载包时,基本函数被屏蔽。如果我为新函数编写额外的文档,则会创建另一个.Rd文件,并与原始基本R函数竞争(R要求您在运行 有没有干净的方法可以做到这一点? 可以使用S4完成。请注意, FYI, looks like this question already has a LISP equivalent. Recently I wanted to create a dataframe extension to the R base function 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 Is there a clean way to do this? It can be done using S4. Note that
这篇关于将R S3普通函数转换为通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!时选择要使用哪一个文件)?setdiff $ c
setdiff
使用x和y作为参数,因此该方法也应该如此:
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,])
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)], ]
}
?setdiff
).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, ])