【问题标题】:How to add additional components to htest object如何向 htest 对象添加其他组件
【发布时间】:2022-01-11 23:44:21
【问题描述】:

我正在尝试编写与 var.test() 非常相似的自己的函数。我希望我的输出看起来类似于 var.test() 的输出,并且似乎 var.test() 将输出列表分配给类 htest。我想做类似的事情,但在输出列表中添加一个附加组件,即级别 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)
}

如果我尝试将变量 alpha 添加到我的输出中,则函数返回的输出没有任何差异。所以,例如

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

【问题讨论】:

    标签: r c function hypothesis-test


    【解决方案1】:

    "htest" 类对象的 print 方法不会打印 conf.int 的属性,但它存在:

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

    如果对象返回子类类"htest" 并且编写了该自定义类的方法,则可以自动打印。
    在测试函数中将类归属指令改写为

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

    或使用另一个类名。然后,编写一个print.feonyte 方法。

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

    另外,返回值没有methodalternativeparameter成员。

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 2011-03-31
      • 2013-10-14
      • 1970-01-01
      • 2019-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多