How to add additional components to htest object

Viewed 27

I am trying to write my own function much similar to var.test(). I would like my output to look similar to that of var.test(), and it seems that var.test() assigns the output list to the class htest. I want to do something similar, but add an additional component to the output list, that being the level alpha.

testvar <- function(x1, x2, level = 0.95) {
  df1 <- length(x1) - 1
  df2 <- length(x2) - 1
  alpha = 1 - level
  s1 <- var(x1)
  s2 <- var(x2)
  dataname <- paste(deparse(substitute(x1)), "and", deparse(substitute(x2)))
  if(s1 > s2) {
    ts = s1/s2
    pval = 2 * (1 - pf(ts, df1, df2))
    conf = c(s1/(s2*qf(1-alpha/2, df1, df2)), s1/(s2*qf(alpha/2, df1,df2)))
  }
  else if(s2 >= s1) {
    ts = s2/s1
    pval = 2 * (1 - pf(ts, df2, df1))
    conf = c(s2/(s1*qf(1-alpha/2, df2, df1)), s2/(s1*qf(alpha/2, df2,df1)))
  }
  
  names(ts) = "F"
  attr(conf, "conf.level") <- level
  output <- list(statistic = ts, p.value = pval, conf.int = conf, data.name = dataname)
  attr(output, "class") <- "htest"
  return(output)
}

If I try to add the variable alpha to my output, it fails to have any difference in the output returned by the function. So, for example

output <- list(statistic = ts, p.value = pval, conf.int = conf, data.name = dataname, level)
1 Answers

The print method for objects of class "htest" doesn't print the attribute of conf.int but it's there:

set.seed(2021)
x <- rnorm(100)
y <- rnorm(100)
ht <- testvar(x, y)
attributes(ht$conf.int)
#$conf.level
#[1] 0.95

This can be automatically printed if the object returned subclasses class "htest" and a method for that custom class is written.
In the test function rewrite the class attribution instruction as

attr(output, "class") <- c("feonyte", "htest")

or using another class name. Then, write a print.feonyte method.

print.feonyte <- function(x, ...){
  NextMethod(x, ...)
  alpha <- attr(x$conf.int, "conf.level")
  cat("confidence level:", alpha, "\n\n")
  invisible(NULL)
}

ht

Also, the return value does not have method, alternative and parameter members.

Related