Waldir Leoncio
Waldir Leoncio

Reputation: 11341

How to make a generic R function inherit the class of its input?

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.

Upvotes: 4

Views: 191

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269481

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"

Upvotes: 4

Related Questions