问题
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