简体   繁体   中英

Do R classes change numeric values?

As I already had similar problems here , I just hit another question: stats::t.test returns a p-value < 2.2e-16 . But from maths I get p_value <- 2 * pt(-abs(t), df) # [1] 1.929352e-17 . What is wrong?

I just started debugging as suggested there:

debug(stats:::t.test.default)
vals <- data.frame(a = c(4, 2, 4, 7, 3, 4, 8, 8, 3, 0, 1, 5, 4, 6, 4, 8, 7, 
                         9, 6, 6, 3, 6, 7, 4), 
                   b = c(5, 7, 6, 13, 12, 6, 14, 16, 4, 2, 7, 7, 4, 8, 9, 9, 
                         11, 13, 12, 8, 3, 8, 7, 7))

stats::t.test(x = vals)
# One Sample t-test
# data:  vals
# t = 13.214, df = 47, p-value < 2.2e-16

Then you step through until you reach line 98,

在此处输入图片说明

where pval is evaluated as 1.929352e-17 , which I expected. This remains unchanged until line 112, where the class is set class(rval) <- "htest" .

在此处输入图片说明

What is wrong? Do classes change values? Unfortunately, I don't know, how to understand / debug the code behind line 112.

No. Classes don't change values, but they do change how they are printed. Since the class that's being returned is a htest object, the stats:::print.htest() is used to draw the result. To make things prettyier, this function formats numbers so they have a reasonable number of decimal places. It uses the format.pval function to make p-values look pretty. After p-values get really small it doesn't really make sense to show all the digits so R just tells you at some point it's less than a certian value. For example

format.pval(1e-20)
# [1] "< 2.22e-16

The "real" value is still stored in the object

x <- stats::t.test(x = vals)
x$p.value
# [1] 1.929352e-17

This is a very common pattern in R where just print() ing a value doesn't necessarily show what's "really" there; it's just a pretty display of that object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM