Reputation: 5789
So I'm making an R package. In this package, I have a function foo1
that returns an S3
list whose component can be ploted. Right now I have a function plotfoo1
which does that. E.g. the following currently works:
output1<-foo1(Data)
plotfoo1(output1)
Now my question. I want to override the plot function in R such that the following would yield the same output:
plot(output1)
but I don't know how to do that. I'm looking for (a link?) explaining how to do that. It should be possible as it seems that many packages have thei own custom plot function...
Upvotes: 3
Views: 1751
Reputation: 61923
You don't want to overwrite plot.default
- that would be a terrible idea. What you probably should do instead is make it so that foo1
returns an object with a class that you create and write a S3 plot method for that class type. Here is an an example
foo1 <- function(){
dat <- data.frame(x = 1:10, y = rnorm(10))
# Give the data a class
class(dat) <- "myclass"
return(dat)
}
# Write plot function for objects that
# have class "myclass"
plot.myclass <- function(obj, ...){
plot.default(obj$x, obj$y)
}
mydata <- foo1()
# See - it has class "myclass"
class(mydata)
# plot recognizes that mydata has class "myclass"
# and calls plot.myclass on mydata automatically
plot(mydata)
Upvotes: 7