Mathematical formula underlying t.test function in R

Viewed 40

does someone know which mathematical formula is used by R to perform the t-test?

If I look on Internet, if find different possible mathematical formulas: I tried to my t-test "by-hand" with the 3 following formulas (that you can see in the 2 following pictures):

enter image description here

enter image description here

Yet, if, I compare the p-values that i find with the one that the t.test function in R gives me, I get very different results. -> When I try with the 3 different formulas, I get non-significant p-values each time. -> When I try with the r function,I get a significant p-value.

Here is my code:

#Loading the data
library("lingpsych")
data("df_gibsonwu")

#Preparing the data
bysubj <- aggregate(rt~subj + type, mean, data=df_gibsonwu)
ORSR <- bysubjOR$rt - bysubjSR$rt
meanOR <- mean(bysubjOR$rt)
meanSR <- mean(bysubjSR$rt)

# Paired t-test by hand:
n <- 37

SE0 <- sqrt(((sd(bysubjOR$rt)^2) /n)+((sd(bysubjSR$rt)^2)/n))
SE1 <- sqrt(((n * sum(ORSR))^2 - (sum(ORSR)))^2 / n-1)
SE2 <- sd(bysubj$rt) / sqrt(n)

tvalue0 <- (meanOR - meanSR) / SE0
tvalue1 <- (sum(ORSR)) / SE1 #Which I think, is the correct formula for a paired-t-test?
tvalue2 <- (meanOR - meanSR) / SE2

critT <- qt(0.975,n-1)
pvalue0 <- 2*(pt(tvalue0, n-1, lower.tail=FALSE))
pvalue1 <- 2*(pt(tvalue1, n-1, lower.tail=FALSE))
pvalue2 <- 2*(pt(tvalue2, n-1, lower.tail=FALSE))

# Paired t-test using the R function:
t.test(bysubj$rt ~ bysubj$type, paired=TRUE)

The results are the following: pvalue0 = 1.959, pvalue1 = 1.000, pvalue2 = 1.994,

p-value with the r function: 0.01248

Thank you in advance for your help! :)

1 Answers

You need to make sure you rearrange/pair up your data properly.

bysubj <- aggregate(rt~subj + type, mean, data=df_gibsonwu)
dd <- data.frame(obj = bysubj[bysubj$type=="obj-ext", "rt"],
                 subj = bysubj[bysubj$type=="subj-ext", "rt"])

calculate x diffs, variances, n by group

xdiff <- dd[,1] - dd[,2]
n <- nrow(dd)

t statistic (according to formula above)

tstat <- mean(xdiff)/sqrt(var(xdiff)/n)
## -2.63007

As @rawr suggested in comments, I got this from looking at the code of stats:::t.test.default

calculating the p-value

using 2*pt(abs(), ..., lower.tail = FALSE) gets us the two-tailed p-value for either a negative or a positive t-statistic.

df <- n - 1
2*pt(abs(tstat), df, lower.tail  = FALSE)
## 0.01248

With t.test():

t.test(dd$subj, dd$obj, paired = TRUE)
## t = 2.6301, df = 36, p-value = 0.01248
Related