Make a existing function generic

瘦欲@ 提交于 2021-02-11 15:29:45

问题


I want to make an existing function generic. Thereby the default case should be the same as before, but I want to add a case for my own data structure.

Thereby I came around setGeneric. For classes like data.frame it works like expected, but for my own class (class attribute set) it just calls the default function:

> setGeneric('dim')
> dim.data.frame <- function(x) 42
> df <- read.csv('test.csv')
> dim(df)
42

If I exchange data.frame with my own class it doesn't work and just calls the default dim function.


回答1:


Here is how the Rstudio Team replaces existing functions to make them a generic with the condition you asked for: the existing function becomes the default.

https://github.com/tidyverse/dplyr/blob/master/R/sets.r

I would do it this way:

dim <- function(x) UseMethod("dim")

dim.default <- function(x) base::dim(x)

dim.test <- function(x) 42

dim(mtcars)
#> [1] 32 11

mydata <- mtcars
class(mydata) <- "test"
dim(mydata)
#> [1] 42



回答2:


I can not reproduce your problem. For me:

dim.test <- function(x) 23
x <- 2
class(x) <- "test"
dim(x) 

returns 23, as expected



来源:https://stackoverflow.com/questions/59056308/make-a-existing-function-generic

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