Klaus Hoejlund
Klaus Hoejlund

Reputation: 1

Doornik & Hansen normality test using R (normality.test2)

I am testing for normality using the (adjusted) Doornik-Hansen test in R: normwhn.test::normality.test2. The test works fine, but I would like to extract specific elements from the test, i.e. the test statistic (Ep) and the significance of the test statistic (Sig.Ep). I have the following line of code defining a metrix/vector and then test for normality:

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

Can any of you explain to me how i extract a certain element? I have tried to use brackets, e.g. normality.test2(m_1)[1] but without succes.

Upvotes: 0

Views: 519

Answers (1)

lefft
lefft

Reputation: 2105

If you look at the source code of normwhn.test::normality.test2 (just evaluate it without parentheses), you'll see that all the info you want is just printed to the screen, not part of the return value. For example these are the last few lines:

  ...
  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)
}

So the two best options would be:

  1. just re-write the function, returning a list of all the things you want instead of printing them; or
  2. wrap the call to normality.test2 in capture.output() to return everything that was printed (see this question for reference).

Option 2. might take less effort up front, but the results will get returned as a character vector (one element for each line printed to the console), and you'll have to parse that to get what you want.

An example of strategy 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))

You can then start parsing the output with e.g.:

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

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

(fwiw, if I were you, I would just grab the code of the function and rewrite it so that it returns what you want. Much easier in the long run. Maybe even consider sending the authors a message, and asking if they'd consider introducing a parameter like output_in_return_value.)

Upvotes: 1

Related Questions