Safely creating S3 Generics in R

蓝咒 提交于 2019-12-04 15:03:40

问题


Henrik Bengtsson has provided the internet with a nice way of creating S3 generics in R without having to bother whether they were already created before... in 2002.

What his function setGenericsS3 does, is basically:

  • check whether the name is fine
  • check whether there is a function with that name

if so,

  • check whether it is a generic
  • in case it's not, rename it as .default and create a generic

if not, just create the generic.

This code proved very useful to automatically create generics when there was none available in your own packages. As we moved quite past this R era, I was wondering what the correct way is to achieve the same in R now. I can't find an isS3Generic() or similar function in R, and the code of Henrik Bengtsson originates from long before the obligatory namespaces as introduced in R 2.14. I remember I've seen other ways of achieving the same, but can't locate them.

EDIT : I'm specifically looking for S3. The function isGeneric() only works for S4, eg for anova (which is a S3 generic) :

> isGeneric('anova')
[1] FALSE
> anova
function (object, ...) 
UseMethod("anova")
<bytecode: 0x04dc7a18>
<environment: namespace:stats>

回答1:


You can use isGenericS3 function of the R.methodsS3 package. Please see the code below:

library(R.methodsS3)
isGenericS3(anova)
# [1] TRUE


来源:https://stackoverflow.com/questions/8474872/safely-creating-s3-generics-in-r

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