Hypothesis Testing: t-test solution page and R scripts

The following R script will calculate the p-value for Question 1.

You can copy and paste the code into R and it should run without modification. You can download R for free from  R  https://www.r-project.org/ or you can copy and paste the code into a free online R compiler such as: rextester   https://rextester.com/l/r_online_compiler or JDOODLE  https://www.jdoodle.com/execute-r-online

mux = 7;                      
xbar = 8.1; Sx =2.3; n = 36;  
t_statistic = (xbar - mux)/(Sx/sqrt(n));                 "t_statistic"; t_statistic;
pvalue = pt(t_statistic, df = n-1, lower.tail = FALSE);   "pvalue";     pvalue;
# end of R script

R returns:
[1] “t_statistic”
[1] 2.869565

[1] “pvalue”
[1] 0.003462968

The following figure shows the t-distribution from Question 1’s solution. The area of the shaded red region in the right tail equals the p-value.

End of the solution to question 1.
Click here to return to the Hypothesis Testing: t-test questions page.


The following R script will calculate the p-value for Question 2 and produce a graph of the t-distribution.

You can copy and paste the code into R and it should run without modification. You can download R for free from  R  https://www.r-project.org/ or you can copy and paste the code into a free online R compiler such as: rextester   https://rextester.com/l/r_online_compiler or JDOODLE  https://www.jdoodle.com/execute-r-online

# R script to calculate p-value and graph the t-distribution
mux = 9;                      
xbar = 9.4; Sx =2.2; n = 40;  
t_statistic = (xbar - mux)/(Sx/sqrt(n));                 "t_statistic"; t_statistic;
pvalue = pt(t_statistic, df = n-1, lower.tail = FALSE);   "pvalue";     pvalue;
# graph t distribution
tvals <- seq(-4, 4, length=100)
degf <- c(n-1)
mainString = paste("t-distribution with df = n - 1 = ",
toString(n-1),
"\n p-value = area of region shaded red = ",
toString(round(pvalue,5)));
plot(tvals, dt(tvals,df = n-1),
lwd=4, col="blue", type="l", lty=2, xlab="t-statistic",
ylab="Density", main= mainString )
grid(lwd = 2, col = "black")
lines(tvals, dt(tvals,df = n-1), lwd=4, col="blue", type="l", lty=1)
for(i in 1:1000){
lines(c(t_statistic + ((4 - t_statistic)/1000)*i, t_statistic + ((4 - t_statistic)/1000)*i),
c(0,dt(t_statistic + ((4 - t_statistic)/1000)*i, n-1)), lwd = 3, col = "red");
}
lines(c(-4.3, 4.3), c(0,0), lwd = 2);
ticks = c(t_statistic)
axis(side = 1, at = ticks)
#End of R script

R returns:

[1] “t_statistic”
[1] 1.149919

[1] “pvalue”
[1] 0.12859

R also returns the following figure showing the t-distribution from Question 2’s solution. The area of the shaded red region in the right tail equals the p-value.

End of the solution to question 2.
Click here to return to the Hypothesis Testing: t-test questions page.