0

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.

Querenker
  • 2,242
  • 1
  • 18
  • 29
  • Can show the code that is NOT working as desired? – SmokeyShakers Nov 26 '19 at 18:03
  • Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) showing how your classes are different. It's hard to see what might be wrong if we cannot reproduce the error you are experiencing. – MrFlick Nov 26 '19 at 18:54

2 Answers2

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
Edo
  • 7,567
  • 2
  • 9
  • 19
  • Thanks for your solution. Unfortunately this will not work if e.g. `nrow` or `ncol` gets called. There the base dim is used and not my function for my own data type. – Querenker Nov 26 '19 at 21:14
  • Then why don’t you just overwrite in the same way the functions nrow and ncol? I think if you provide a bit more details about your problem and your goal we can come up with a solution – Edo Nov 26 '19 at 21:28
  • Actually, if you try to run nrow(mydata) it will return 42, while ncol(mydata) will return NA, as expected. Maybe I’m missing something here that you want to achieve – Edo Nov 26 '19 at 21:33
0

I can not reproduce your problem. For me:

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

returns 23, as expected

akraf
  • 2,965
  • 20
  • 44