【问题标题】:Doornik & Hansen normality test using R (normality.test2)Doornik & Hansen 使用 R (normality.test2) 进行正态性检验
【发布时间】:2018-03-18 14:21:26
【问题描述】:

我正在使用 R 中的(调整后的)Doornik-Hansen 测试来测试正态性:normwhn.test::normality.test2。测试工作正常,但我想从测试中提取特定元素,即测试统计量(Ep)和测试统计量的显着性(Sig.Ep)。我有以下代码行定义一个矩阵/向量,然后测试正常性:

m_1 <- matrix(data[,2], nrow = nrow(data), ncol = 1)
normality.test2(m_1)

谁能向我解释我如何提取某个元素?我尝试使用括号,例如normality.test2(m_1)[1] 但没有成功。

【问题讨论】:

  • 也许添加库和可重现的数据。我测试过了,看来你最好的选择是capture.output(normality.test2(m_1))
  • 先尝试将返回值存储在变量中并检查类。这可能是一个列表。

标签: r


【解决方案1】:

如果你看normwhn.test::normality.test2的源码 (只需评估它,不带括号),你会看到你所有的信息 want 只是打印到屏幕上,而不是返回值的一部分。例如,这些是最后几行:

  ...
  dof <- 2 * nvars
  sig.Ep <- 1 - pchisq(Ep, dof)
  print("H0: data are normally distributed")
  print("Ep")
  print(Ep)
  print("dof")
  print(dof)
  print("sig.Ep")
  print(sig.Ep)
}

所以两个最好的选择是:

  1. 只需重新编写函数,返回您想要的所有内容的列表 而不是打印它们;或
  2. 将对normality.test2 的调用包装在capture.output() 中以返回打印的所有内容(参见this question 以供参考)。

选项 2. 可能需要较少的前期工作,但结果将作​​为字符向量返回(每行一个元素打印到控制台),您必须对其进行解析才能获得所需的内容。

策略 2 的示例:

data <- matrix(rnorm(100), ncol=2)
m_1 <- matrix(data[,2], nrow = nrow(data), ncol = 1)
test_result_output <- capture.output(normwhn.test::normality.test2(m_1))

然后您可以开始解析输出,例如:

gsub("\"|\\[,*1,*\\]", "", test_result_output)

## ...
## ...
## [32] " Ep"                                    
## [33] "         "                              
## [34] " 1.512684"                              
## [35] " dof"                                   
## [36] " 2"                                     
## [37] " sig.Ep"                                
## [38] "          "                             
## [39] " 0.4693803"  

(fwiw,如果我是你,我会抓住函数的代码并重写它,以便它返回你想要的。从长远来看会容易得多。甚至可以考虑向作者发送消息,并询问是否他们会考虑引入像output_in_return_value 这样的参数。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2021-07-10
    • 2022-11-15
    相关资源
    最近更新 更多