JMichael
JMichael

Reputation: 564

Why can't I round cor.test

I'm working on measuring the correlation between Month & Temp from the Mitchell data (comes with the alr3 package). I wanted to round the coefficient to the nearest thousandth, but when I added round() to the code I got this error:

Error in round(cor.test(Month, Temp), 3) : 
  non-numeric argument to mathematical function

However, if I swap cor.test with cor the rounding works. What about cor.test is causing the issue? And how can I adjust my code (below) to allow the rounding to work?

with(Mitchell, round(cor.test(Month, Temp), 3))

Upvotes: 0

Views: 751

Answers (1)

A. Webb
A. Webb

Reputation: 26446

See the help file for cor.test. The cor.test function returns a list with an htest class attribute rather than a numeric vector required by round.

Example from the help file:

x<-cor.test(~ CONT + INTG, data = USJudgeRatings)

is.numeric(x)
#> [1] FALSE
class(x)
#> [1] "htest"

You may just want to pretty print using a different number of digits, in which case you could look at the print function for this class.

getAnywhere(print.htest)

However, even though there is a digits argument, it is respected only for the p-value. So, you'll just have to do your own rounding:

structure(rapply(z,function(x) if(is.numeric(x)) round(x,3) else x,how="replace"),
  class="htest")
        Pearson's product-moment correlation

data:  CONT and INTG
t = -0.861, df = 41, p-value = 0.395
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.417  0.174
sample estimates:
   cor 
-0.133 

Upvotes: 2

Related Questions