简体   繁体   中英

My S3 generic function stops working after calling a print function in R

I created a generic function and defined the class of the output within the function. I also created a print function that takes the output of the first function.

However, after I run print, the original function gives the output of print rather than the output I want it to give.

These are my methods:

fisher <- function(obj, ...){
  UseMethod("fisher")
}

fisher.default <- function(obj, ...){
  x<- -2*sum(log(obj))
  df <- 2*length(obj)
  p = pchisq(x, df,lower.tail = FALSE)
  class(p)="fisher"
  p
}

print.fisher <- function(print_obj){
  paste("The p-value of this vector is: ", print_obj)

}

xx= fisher(x)

fisher worked perfectly fine before creating and executing the print.fisher function. Now fisher(x) gives the exact output as print(xx) .

What could possibly be going wrong?

The following works with me. R 4.0.3 on Ubuntu 20.10.

fisher <- function(x, ...){
  UseMethod("fisher")
}

fisher.default <- function(x, ...){
  y <- -2*sum(log(x))
  df <- 2*length(x)
  p <- pchisq(y, df, lower.tail = FALSE)
  class(p) <- c("fisher", class(p))
  p
}

print.fisher <- function(x, ...){
  y <- paste("The p-value of this vector is:", unclass(x))
  print(y)
  invisible(y)
}

set.seed(2020)
x <- abs(rnorm(10))
xx <- fisher(x)
xx
#[1] "The p-value of this vector is: 0.985718045451049"

Running the function without assigning the output also calls the custom print method.

fisher(x)
#[1] "The p-value of this vector is: 0.985718045451049"

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