将R S3普通函数转换为通用函数 [英] Turning an R S3 ordinary function into a generic

查看:127
本文介绍了将R S3普通函数转换为通用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FYI,看起来像这个问题已经有一个 LISP等效

a>。

最近我想为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要求您在运行时选择要使用哪一个文件)?setdiff

有没有干净的方法可以做到这一点?

解决方案

可以使用S4完成。请注意, 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,])


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

这篇关于将R S3普通函数转换为通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆