Reputation: 7592
Suppose I want to create a method for a class I've created, but I don't have access to the code of the original function - I just want to build on top of it. Just to give a simple example that doesn't actually do anything:
x1<-1
class(x1)<-c("myclass",class(x1))
print.myclass<-function(x) {
x<-paste0(x,"foobar")
print(x)
}
print(x1)
If I try to run the last line, it throws the function into a loop and R eventually crashes. The solution I found was to add a line to the function that strips the new class name from x
before passing it to the original function:
print.myclass<-function(x) {x<-paste0(x,"foobar"); class(x)<-class(x)[-1]; print(x)}
Is there a better/best practice way to do it?
Upvotes: 0
Views: 38
Reputation: 7063
I think your problem is that you create an infinite loop: print(print(...)
.
I don't know what you want to achieve but this might be what you are looking for:
x1 <- 1
class(x1) <- c("myclass",class(x1))
print.myclass <- function(x) print.default(x)
print(x1)
Perhaps you might want to look here
BTW: I don't think your solution really solves the problem. You just delete your new class entry which causes print
not to use print.myclass
.
For details see Hadley
Upvotes: 2