4

Let the following code:

x <- 1:5
class(x) <- "bar"

foo <- function(x) {
    UseMethod("foo")
}

foo.bar <- function(x) {
    y <- max(x)
    return(y)
}

I would like the output of foo(x) to have the same class as x (i.e., "bar"). The obvious way to do it is to add a class(y) <- class(x) inside foo.bar(), but I would like to know if/how I could do that in foo() itself.

The reason for this is that my real case has several generics, each one with 10+ methods, so if I could inherit the class in the generics, I'd just have to modify those instead of tens of methods.

Waldir Leoncio
  • 10,853
  • 19
  • 77
  • 107
  • "but I would like to know if I could do that in foo() itself" No, you can't. Think about what you are asking. Methods are free to return anything. How should the generic then enforce something regarding their return values? – Roland Sep 06 '21 at 09:06

1 Answers1

4

Rename foo to foo_, say, and then define foo to call foo_ and then set the class.

foo_ <- foo
foo <- function(x) structure(foo_(x), class = class(x))
foo(x)

giving:

[1] 5
attr(,"class")
[1] "bar"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341