简体   繁体   中英

Dispatch plot() for own R package

I'm trying to dispatch S3 generic plot() for my CRAN package by using class() and it generates this error:

    Error in xy.coords(x, y, xlabel, ylabel, log) : 
      'x' and 'y' lengths differ

But without the use of class() code is working fine. Kindly correct my mistake. Here is my R code:

plot.myclass<-function(y,k,h){
  UseMethod("plot")
  n <- length(y)
  x <- seq(min(y) + 0.05, max(y), length = k)

  KErlang <- matrix(rep(0, k * n), ncol = k)
  fhat <- rep(0, k)
  ###########erlang###########
  for(j in 1:k) {
    for(i in 1:n) {
      KErlang[i, j] <-(1/(gamma(1+(1/h))))*((1/x[j])*(1+(1/h)))^((h+1)/h)*y[i]^(1/h)*exp(-y[i]/x[j]*(1+(1/h)))
    }
    fhat[j] <- 1/n * (sum( KErlang[, j]))
    d1<-density(y,bw=h)
    class(x)<-"myclass"
  }  
}
y<-rexp(200,1)
h<-0.79 * IQR(y) * length(y) ^ (-1/5)
plot(y,200,h)

Three issues:

Your function doesn't plot anything. plot.myclass should have an argument list function(x, y, k, h, ...) (it needs to be compatible with the arguments to plot , but can include more arguments), and can assume that x has class myclass . It should use this assumption to construct a plot of it.

Only the generic function plot should call UseMethod("plot") . Your method should never call that.

Finally: You call the generic using plot(y,200,h) , but at that point in your code, y does not have a class, so your plot.myclass method will not be called. You'll just get the default plot method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM