R Lab Hypothesis Testing
R Lab Hypothesis Testing
• To get critical values of the z-score in R for one-tailed and two-tailed tests, you can use
the qnorm() function.
• For a one-tailed test with a significance level of α, the critical value is the z-score that
corresponds to a cumulative probability of 1-α in the standard normal distribution.
Example
For example, to get the critical value of the z-score for a one-tailed test with a significance level
of 0.05 (i.e., α=0.05) in R, you can use the following code:
4. P-value
• To get the critical values for a t-test in R, we can use the qt() function.
• The qt() function takes three arguments: p, df, and lower.tail.
• The p argument specifies the probability of the tail, df specifies the degrees of freedom,
and lower.tail specifies whether to calculate the critical value for the lower tail or upper
tail of the t-distribution.
Example
If we want to find the t critical value for a left-tailed, right-tailed and two-tailed tests with a
significance level of .05 and degrees of freedom = 22, we can use the following example code:
#find t critical value (left-tail test)
qt(p=.05, df=22, lower.tail=TRUE)
[1] -1.717144
#find t critical value (right-tail)
qt(p=.05, df=22, lower.tail=FALSE)
[1] 1.717144
#find two-tailed t critical values
qt(p=.05/2, df=22, lower.tail=FALSE)
[1] 2.073873
#find p-value
pt(q=-.77, df=15, lower.tail=TRUE)
[1] 0.2266283
# find two-tailed p-value
p_value <- 2 * pt(q = abs(2.5), df = 10, lower.tail = FALSE)
p_value
[1] 0.03144684
Example
A researcher wants to test whether there is a significant difference in the mean scores of two
groups of students (Group A and Group B) on a math test. The mean score for Group A is 85 with
a standard deviation of 6, while the mean score for Group B is 90 with a standard deviation of 7.
The sample size for both groups is 30. The researcher decides to use a significance level of α =
0.05.
What is the calculated t-value and p-value for this experiment?
Solution
x1_bar = 85
x2_bar = 90
s1 = 6 # sample1 standard deviation
s2 = 7 # sample2 standard deviation
n1 = 30 # size of sample1
n2 = 30 # size of sample2
#Computing t-statistics
t = (x1 - x2) / (s1 /sqrt(n1)) + (s1/sqrt(n2))
t
[1] -3.46891
# critical value for a two-tailed test
qt(p=.05/2, df=58, lower.tail=FALSE)
[1] 2.001717
# P-value
p_value <- 2 * pt(q = abs(-3.46891), df = 58, lower.tail = FALSE)
p_value
[1] 0.0009920902
Example
Dependent t-test
To calculate the dependent t-test manually, you can follow these steps:
weight_data$dif <-weight_before-weight_after
head(weight_data,5)
id weight_before weight_after dif
1 1 60 61 -1
2 2 65 64 1
3 3 70 72 -2
4 4 72 70 2
5 5 68 70 -2
Calculate the p-value using the cumulative distribution function of the t-distribution: