generated from jtr13/bookdown-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
10-Inferential.Rmd
1419 lines (814 loc) · 61.5 KB
/
10-Inferential.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Two Sample Inferential Statistics
```{r, echo=FALSE, warning=FALSE, message=FALSE}
library(tidyverse)
```
A very common question in statistics is whether two groups differ from each other in their distributions. Most often, what we are really asking is whether the population means $\mu$ of two groups differ from each other.
In the figure below, we are plotting four different comparisons of two normal distributions.
In the top left, both populations have the same mean $\mu$ and same variance $\sigma^2$ (remember that variance is standard deviation $\sigma$ squared). These two populations are essentially identical. In the top right, both populations have the same mean $\mu$, but differ in their variance $\sigma^2$.
The bottom two distributions show populations with different population means $\mu$ and the same variance $\sigma^2$. In the bottom left, the means are quite far apart, whereas in the bottom right the means are different to each other but the effect is much smaller.
<br><br>
![](img/compare_dists.png)
<br><br>
It is also possible to have the situation where the means are different to each other, and so is the variance, as is shown in the figure below:
<br><br>
![](img/compare_dists1.png)
<br><br>
## Independent Samples t-test
The most typical situation where we are interested in comparing two means is when we collect two samples of data. Perhaps we collect data on the reaction times of subjects after drinking water or coffee. We would be able to directly calculate the sample means $\overline{x}$ of both samples and could find out if there was a different or not in these values. But, what we really want to know is whether the respective populations that these two samples come from (i.e. the population of water drinkers vs the population of coffee drinkers) actually differ in their population means $\mu$.
This is the situation that we will discuss more in this chapter. **Independent t-tests** examine whether two independent samples (meaning different individuals in each group) could theoretically have come from populations with the same population mean $\mu$, or whether this is unlikely and their populations likely had different population means $\mu$. Independent t-tests also get called **two-sample t-tests**.
There are two types of independent t-tests. The first, and the one that we will discuss most extensively, is called the **Student's t-test**. This test assumes that the populations we are comparing have the same variances $\sigma^2$. The other independent t-test is called the **Welch's t-test** and makes a correction that allows for the two populations we are comparing to have different variances $\sigma^2$. We will talk more about this version when performing t-tests in R, as it is actually the default version that R performs. For now, we shall dive deeper into the principles behind the Student's t-test.
## Sampling Distribution of the Difference in Sample Means
For a two-sample independent $t$-test, the sampling distribution we use is different to the sampling distribution for a one-sample $t$-test. In a one-sample test, we are focused on the sampling distribution of sample means. In a two-sample test we are focused on the *sampling distribution of the differences in sample means*.
### Visualizing the Sampling Distribution
Let's try to illustrate this by looking at the sampling distributions we could get when we draw samples from two populations. In the first example, the populations differ in their means. In the second example, the populations do not differ in their means.
<br>
**Difference in Population Means**
Say we have two normally distributed populations, A and B and each has 500,000 subjects. A has a population mean $\mu = 15$, and a population standard deviation $\sigma = 2.5$. B has a population mean $\mu = 12$, and a population SD $\sigma = 2.5$.
We can generate these population by simulation in R like this:
```{r}
set.seed(1)
A <- rnorm(n = 500000, mean = 15, sd = 2.5)
B <- rnorm(n = 500000, mean = 12, sd = 2.5)
```
We can check their mean and standard deviation, and we see that the standard deviations are identical at 2.5, but the population means differ by 3:
```{r}
# and their summary descriptive stats
mean(A)
sd(A)
mean(B)
sd(B)
```
We can visualize these population distributions as follows:
```{r}
data.frame(A, B) %>%
pivot_longer(1:2) %>%
ggplot(aes(x=value, fill=name)) +
geom_density(alpha = .1) +
theme_classic() +
ggtitle("Comparison of Population A vs B")+
geom_vline(xintercept = 15, color="red", lwd=1, lty=1)+
geom_vline(xintercept = 12, color="dodgerblue", lwd=1, lty=2) +
scale_x_continuous(breaks = seq(2,26,2))
```
We can calculate the true difference in population means $\mu_{A} - \mu_{B}$ to be 2.997.
```{r}
mean(A) - mean(B)
```
If we knew nothing about the populations of A and B, but were interested in whether they differed in their population means, then we might take a sample of A and a sample of B and compare their sample means. In this example, we are going to take a sample of size $n=17$ from population A, and a sample of size $n=20$ from population B. These sample sizes were picked more or less at random - they can be the same sized samples, or they can be different sizes.
Let's take our samples, and then examine the differences in our sample means:
```{r}
set.seed(1) # so we get the same values
a1 <- sample(A, 17)
a1
b1 <- sample(B, 20)
b1
mean(a1)
mean(b1)
mean(a1) - mean(b1)
```
Here we find that the difference in means between our sample from population A and our sample from population B is 2.85. In other words, $\overline{x}_{A} - \overline{x}_{B} = 2.85$ This is pretty close to the true difference in population means (although we're currently pretending that we don't know that difference).
We could do this again. Let's select another sample from population A of size 17, and another sample from population B of size 20:
```{r}
a2 <- sample(A, 17)
a2
b2 <- sample(B, 20)
b2
mean(a2)
mean(b2)
mean(a2) - mean(b2)
```
This time, $\overline{x}_{A} - \overline{x}_{B} = 3.37$ This is again pretty close to the true difference in population means, but a bit higher this time.
We can keep drawing samples of size 17 from A, and size 20 from B and examining the difference in sample means $\overline{x}_{A} - \overline{x}_{B}$. A quick way of writing that code in R is as follows - where we repeat it 5 more times:
```{r}
mean(sample(A,17)) - mean(sample(B,20))
mean(sample(A,17)) - mean(sample(B,20))
mean(sample(A,17)) - mean(sample(B,20))
mean(sample(A,17)) - mean(sample(B,20))
mean(sample(A,17)) - mean(sample(B,20))
```
As you can see, the values we get tend to be a little bit above or a little bit below 3.
If we did this thousands and thousands of times, we'd get a distribution of the differences in sample means. This would be the *sampling distribution of the differences in sample means*. Below we repeat the above step 10,000 times to get a visualization of what this sampling distribution looks like:
```{r}
set.seed(1)
difs <- vector('list', 10000)
for(i in 1:10000){
difs[[i]] <- mean(sample(A, 17)) - mean(sample(B, 20))
}
df <- data.frame(dif = unlist(difs))
#get mean difference
mean(unlist(difs)) # 3.00
#make histogram
ggplot(df, aes(x=dif)) +
geom_histogram(color='black', fill='dodgerblue', alpha=.5, binwidth = .1)+
theme_classic() +
xlab("Difference in Sample Means")+
ggtitle("Sampling Distribution of Difference in Sample Means") +
geom_vline(xintercept = mean(unlist(difs)), lwd=1, color="red")
```
As you can see, the sampling distribution is approximately symmetrical. If we ran it for more simulations, it would become even more symmetrical. The average (mean) difference in sample means across all samples is $\Large \mu_{\overline{x}_{A} - \overline{x}_{B}}= 2.987$ which is approximately equal to the real difference in population means $\mu_{A} - \mu_{B}$.
An obvious next question is what is the standard deviation of this sampling distribution? i.e. the standard deviation of the sampling distribution of the differences in sample means. If we knew this, then we'd be able to describe how likely or unlikely we were to get any particular difference in sample means in terms of how many sampling distribution standard deviations that score is away from the mean.
There are actually two different formulas that we can use to work out the standard deviation - which we will discuss shortly (see section \@ref(pooled-standard-deviation)). In brief, it is a bit trickier to calculate the standard deviation of this sampling distribution compared to the standard deviation of the sampling distribution of sample means, because our difference in sample means uses two different samples each with their own sample standard deviation.
Given we just simulated our sampling distribution of the differences in sample means, we could just look at its standard deviation in R:
```{r}
sd(unlist(difs))
```
This tells us that the standard deviation of this sampling distribution is approximately equal to $\sigma_{\overline{x}_{A} - \overline{x}_{B}}= 0.82$. As well as using the formulas that we will introduce shortly to estimate this value, there is actually another shortcut we could have used too as we know the original population standard deviations. This is not essential to know or remember, as it's not something we would ever do in practice, it's just something to point out in passing.
There is something called [variance sum law](http://onlinestatbook.com/2/summarizing_distributions/variance_sum_law.html). Essentially, if you want to know the difference of two variables, then it is equal to the sum of the variance of the two variables.
Our variables in this scenario are the sampling distributions of sample means for A and B. We can calculate the variance of each by $\sigma^2/n$. If we add them together according to the variance sum law, we get the variance for the difference in these two variables. Then we square-root to get the standard deviation - which is equivalent to our sampling distribution of the difference in sample means standard deviation:
```{r}
sqrt((var(A)/17) + (var(B)/20))
```
Again, this tells us that $\Large \sigma_{\overline{x}_{A} - \overline{x}_{B}}= 0.82$.
However, in practice, we only have our two samples (our one sample of population A and our one sample of population B). We don't know anything else about the sampling distribution or the populations. Therefore we cannot use either of the above methods to calculate the standard deviation of the sampling distribution. We'll get to what method you need to use soon.
<br><br>
**No Difference in Population Means**
Let's look at an example of what the sampling distribution of difference in sample means looks like when there is no difference between population means.
In this scenario, we have two normally distributed populations, C and D and each has 500,000 subjects. C has a population mean $\mu = 10$, and a population standard deviation $\sigma = 3$. D has a population mean $\mu = 10$, and a population SD $\sigma = 3$. We can generate these populations in R:
```{r}
set.seed(1)
C <- rnorm(n = 500000, mean = 10, sd = 3)
D <- rnorm(n = 500000, mean = 10, sd = 3)
```
We can then examine their means and standard deviations:
```{r}
# and their summary descriptive stats
mean(C)
sd(C)
mean(D)
sd(D)
```
We can then calculate the true difference between these populations in their population means and see that $\mu_{C}-\mu_{D} = 0.00$
```{r}
mean(C) - mean(D)
```
We can also visualize these populations - it can be hard to see both populations because they are identical and D is directly on top of C, but they are both there!
```{r}
data.frame(C, D) %>%
pivot_longer(1:2) %>%
ggplot(aes(x=value, fill=name)) +
geom_density(alpha = .1) +
theme_classic() +
ggtitle("Comparison of Population C vs D")+
geom_vline(xintercept = 10, color="red", lwd=1, lty=1)+
geom_vline(xintercept = 10, color="dodgerblue", lwd=1, lty=2)
```
For this example, let's look at one sample of size 11 for population C and one sample of size 14 for population D.
```{r}
set.seed(1)
c1 <- sample(C, 11)
d1 <- sample(D, 14)
c1
d1
mean(c1)
mean(d1)
mean(c1) - mean(d1)
```
Here we find that the difference in sample means $\Large \overline{x}_C - \overline{x}_D = -0.197$.
If we did this lots of times, we'd sometimes get sample means that were larger in C and sometimes they would be larger in D. Let's do it five more times:
```{r}
mean(sample(C,11)) - mean(sample(D,14))
mean(sample(C,11)) - mean(sample(D,14))
mean(sample(C,11)) - mean(sample(D,14))
mean(sample(C,11)) - mean(sample(D,14))
mean(sample(C,11)) - mean(sample(D,14))
```
If we did this thousands and thousands of times, we will get our sampling distribution of the differences in sample means. We can use the code below to simulate this, collecting 20,000 samples of C and D and determining the difference in means for each sample collected:
```{r}
set.seed(1)
difs1 <- vector('list', 20000)
for(i in 1:20000){
difs1[[i]] <- mean(sample(C, 11)) - mean(sample(D, 14))
}
```
We can visualize this sampling distribution:
```{r}
## plot as a histogram:
df1 <- data.frame(dif = unlist(difs1))
ggplot(df1, aes(x=dif)) +
geom_histogram(color='black', fill='mistyrose', alpha=.5, binwidth = .2)+
theme_classic() +
ggtitle("Sampling Distribution of Difference in Sample Means") +
geom_vline(xintercept = mean(unlist(difs1)), lwd=1, color="red")
```
```{r}
mean(unlist(difs1))
```
After 20,000 samples of size 11 from population C and size 14 from population D, we find that the mean difference in sample means is $\mu_{\overline{x}_C - \overline{x}_D} = -0.006$. This is pretty close to the true difference in population means of 0. If we were to run our simulation for longer to get even more differences in sample means, then our mean difference would get even closer to 0.
So, we have a symmetrical sampling distribution of differences in sample means with a mean $\mu_{\overline{x}_C - \overline{x}_D}$ approximately equal to 0.0. What is the Standard Deviation of this distribution? Again, we can calculate this directly from our simulated data:
```{r}
sd(unlist(difs1))
```
Here we find that the standard deviation is $\sigma_{\overline{x}_C - \overline{x}_D} = 1.2$. The question becomes, how do you estimate this standard deviation when you only have one sample of each population? We shall get to how this is done in the next few sections.
## Pooled Standard Deviation
In the Student's t-test, we assume that our two samples come from populations that have "equal variance", i.e. that their standard deviations are equivalent. The reason behind this is that it enables us to use this estimate in calculating the Standard Deviation of the Sampling Distribution of Differences in Sample Means.
When we assume that two samples have the same variance, we estimate this by pooling their standard deviations. Let's look in more detail about how standard deviations are pooled.
When we have two samples, they each have sample standard deviations, that are usually not equal. For example, let's look at these two samples. The first sample is of size 9 and the second sample is of size 10.
```{r}
samp1 <- c(23, 25, 33, 19, 21, 27, 26, 31, 20)
samp1
sd(samp1)
samp2 <- c(21, 22, 23, 19, 20, 24, 25, 21, 23, 22)
samp2
sd(samp2)
```
It's clear that our sample standard deviations differ, with sample 1 having a sample standard deviation $s=4.82$ and sample 2 having a sample standard deviation of $s=1.83$.
So, if we assumed that they both come from populations with the same SD, how do we estimate that value? We have to pool the standard deviation. Essentially, we want to calculate a value that is likely somewhere in between the two sample SDs. In practice we use a weighted average.
There are two ways of going about calculating this pooled standard deviation value. The first is to use first principles as to what a standard deviation is. This is the one that makes most sense logically (to us at least), but it is also the more long-winded way. The second way is to use a shortcut formula.
<br><br>
**Option 1: From first principles**
Let's first calculate the pooled standard deviation based on first principles. Remember, a standard deviation is the square root of the average squared deviation of each value from the mean.
What we could do is to get the difference of every score from it's group mean, then square those differences, then add them all up, then divide by $n-2$, and then square root. We divide by $n-2$ instead of $n-1$ because we have two samples that we are using and we are using two different estimated means to determine the standard deviation. Therefore, to avoid underestimating our standard deviation we divide by $n-2$.
Here, we break this down step by step:
i) Calculate each sample mean:
```{r}
mean(samp1)
mean(samp2)
```
ii) Let's get the differences of each score from their group mean:
```{r}
# get the differences from each group mean:
samp1_dif <- samp1 - mean(samp1)
samp2_dif <- samp2 - mean(samp2)
samp1_dif
samp2_dif
```
iii) Now square all these differences:
```{r}
samp1_dif2 <- samp1_dif^2
samp2_dif2 <- samp2_dif^2
samp1_dif2
samp2_dif2
```
iv) Get the sum of all the squares and add them up across both samples:
```{r}
ssq <- sum(samp1_dif2) + sum(samp2_dif2)
ssq
```
v) Now we get the 'average' squared deviation by dividing by n-2
```{r}
n2 <- 9 + 10 - 2
asd <- ssq/n2
asd
```
vi) Finally, we get the pooled standard deviation by square-rooting this:
```{r}
sqrt(asd)
```
Thus our estimate of the pooled standard deviation is $\hat\sigma_p = 3.56$. This value is between our original sample standard deviations of 4.82 and 1.83, which makes sense.
You may see the following formula for calculating the pooled standard deviation in the way we just did.
$\Large \hat\sigma_p = \sqrt{\frac{\Sigma_{ik}(x_{ik} - \overline{x}_k)^2}{n_1 + n_2 -2}}$
Here, $n_1$ is the sample size of sample 1, $n_2$ is the sample size of sample 2. The $\Sigma_{ik}(x_{ik} - \overline{x}_k)^2$ part of the formula is simply saying to take each data point away from it's sample mean and then square it - and then add all of these up. It looks quite intimidating, but hopefully the steps we outlined above make sense.
<br><br>
**Option 2: Using a shortcut formula**
The second way to calculate the pooled standard deviations doesn't require you to know the raw data. It is a formula that only requires you to know the sample standard deviation of each sample and the sample size of each sample. This is the formula:
$\Large \hat\sigma_p = \sqrt{\frac{w_1s_1^2 + w_2s_2^2 }{w_1 + w_2}}$
Here, $w_1 = n_1-1$ where $n_1$ is the sample size of sample 1. $w_2 = n_2-1$ where $n_2$ is the sample size of sample 2. $s_1$ is the sample standard deviation of sample 1, and $s_1$ is the sample standard deviation of sample 2.
We can calculate the pooled standard deviation using this formula for our two samples above:
```{r}
s1sd <- sd(samp1)
s2sd <- sd(samp2)
w1 <- length(samp1) - 1
w2 <- length(samp2) - 1
numerator <- (w1*s1sd^2) + (w2*s2sd^2)
denominator <- w1+w2
sqrt(numerator/denominator)
```
This approach also calculates the pooled standard deviation to be $\hat\sigma_p = 3.56$.
## Theory behind Student's t-test
Hopefully you have a sense of the sampling distribution for the difference in sample means, and an idea about what pooled standard deviation is. In this section we'll bring together these ideas to show you the behind the scenes working of the Student's t-test.
We'll use some example data from [the Navarro book](https://learningstatisticswithr.com/book/ttest.html#studentttest). These data are the exam scores of students who were TA-ed by either Anastasia or Bernadette. The question at hand is whether these two samples could have come from populations with the same mean, or from populations with different means. We assume that the variance (and therefore standard deviations) of both of these populations are the same.
Here are the data:
```{r}
anastasia <- c(65, 74, 73, 83, 76, 65, 86, 70, 80, 55, 78, 78, 90, 77, 68)
bernadette <- c(72, 66, 71, 66, 76, 69, 79, 73, 62, 69, 68, 60, 73, 68, 67, 74, 56, 74)
```
We can make a boxplot to compare the two samples:
```{r}
# plot the data:
d <- data.frame(values = c(anastasia, bernadette),
group = c(rep("anastasia",15), rep("bernadette", 18))
)
ggplot(d, aes(x = group, y = values, fill = group)) +
geom_boxplot(alpha=.3) +
geom_jitter(width=.1, size=2) +
theme_classic() +
scale_fill_manual(values = c("firebrick", "dodgerblue"))
```
We can also get the sample mean $\overline{x}$, standard deviation $s$ and $n$ of each sample:
```{r}
mean(anastasia)
sd(anastasia)
nA<-length(anastasia)
nA
mean(bernadette)
sd(bernadette)
nB <- length(bernadette)
nB
```
Although we are actually interested in whether these two samples come from populations that differ in their population means, we can directly measure if the two samples differ in their sample means by subtracting one from the other:
```{r}
mean(anastasia) - mean(bernadette)
```
We can see that Anastasia students have on average 5.48 higher scores than Bernadette students. But how meaningful is this difference?
What we are going to do is to work out how unusual or usual our one observed sample mean difference is. We need to construct the sampling distribution of differences in sample means. We hypothesize that the true mean difference in population means is 0 (no difference between groups).
These are our hypotheses:
<br>
$H_{0}: \mu_A = \mu_A$
<br>
$H_{1}: \mu_A \ne \mu_A$
<br>
If we assume that the true difference in population means is 0 (the null hypothesis), then this will mean that the mean of the sampling distribution of the difference in sample means will also be 0 ($\mu_{\overline{x}_A-\overline{x}_B}=0$). If we know the standard deviation of this sampling distribution, then we could work out how many standard deviations away our one observed sample mean difference of 5.48 is from 0. That would enable us to work out the probability of getting a value that extreme.
So our next step is to work out the standard deviation of the sampling distribution. If we assume equal variances between the populations of group A and B, then we can calculate the standard deviation of this sampling distribution as
$\Large \sigma_{\overline{x}_A-\overline{x}_B} = \hat\sigma_p \times \sqrt{\frac{1}{n_1} + \frac{1}{n_2} }$
So, the first step in this formula is to calculate the pooled standard deviation $\hat\sigma_p$. We can either calculate this from first principles or using the shortcut formula (see section \@ref(pooled-standard-deviation)). Below, we calculate the pooled standard deviation using the first principles:
```{r}
# from first principles, calculating deviations from each group mean
difA2 <- (anastasia - mean(anastasia))^2
difB2 <- (bernadette - mean(bernadette))^2
sumsq <- sum(difA2) + sum(difB2)
n <- nA + nB #33
sd.pool <- sqrt(sumsq/(n-2))
sd.pool # 7.41 this is the estimated pooled s.d.
```
This gives us a value of $\hat\sigma_p = 7.407$. This makes sense being in between our two sample standard deviations:
```{r}
sd(anastasia) #8.999
sd(bernadette) #5.775
```
Once we've calculated the pooled standard deviation $\hat\sigma_p$, we can insert it to the formula above to calculate the standard deviation of the sampling distribution of differences in sample means $\sigma_{\overline{x}_A-\overline{x}_B}$.
```{r}
sedm <- sd.pool * sqrt( (1/nA) + (1/nB))
sedm # this is the Standard Deviation of the Sampling Distribution of differences in sample means
```
Doing this, we calculate $\sigma_{\overline{x}_A-\overline{x}_B} = 2.59$. This tells us that the standard deviation of the theoretical sampling distribution of the differences in sample means is 2.59. With that information, we can work out how many standard deviations away from the mean (of 0) our one observed difference in sample means of $\overline{x}_A - \overline{x}_B = 5.48$ is.
Lets' visualize what this sampling distribution looks like:
<br>
![](img/tt5.png)
By estimating the standard deviation, we are able to plot what our sampling distribution would look like. We are then able to see that our observed difference in sample means of $\overline{x}_A - \overline{x}_B = 5.48$ is quite far away from the hypothesized mean of 0 in terms of standard deviations. What we have not discussed so far is what kind of shape that this distribution is other than it is symmetrical. Similar to when we were looking at sampling distributions of sample means (see section \@ref(sampling-distribution-of-the-difference-in-sample-means)), the shape of this sampling distribution of the difference in sample means is also $t$-shaped. In the example given above, it is a $t$-distribution with 31 degrees of freedom. The degrees of freedom of these sampling distributions are equal to $df = n_A + n_B - 2$. So in our case, this is equal to:
```{r}
nA + nB - 2
```
Given that the shape of our distribution is $t$-shaped, when we determine how many standard deviations away from the mean our single observed difference in sample means is, we call this our *observed t-value*.
We calculate t by the following formula:
$\Large t = \frac{(\overline{x}_A - \overline{x}_B) - (\mu_{\overline{x}_{A} - \overline{x}_{B}})}{\sigma_{\overline{x}_{A} - \overline{x}_{B}}}$
But because we assume the mean of the sampling distribution of sample means to be zero, we can write it as:
$\Large t = \frac{\overline{x}_A - \overline{x}_B}{\sigma_{\overline{x}_{A} - \overline{x}_{B}}}$
Essentially, it is taking our observed difference in sample means and dividing it by the standard deviation of the sampling distribution.
```{r}
tobs <- (mean(anastasia) - mean(bernadette)) / sedm
tobs
```
Our observed t-value is $t = 2.115$.
Our final thing to do is to calculate the p-value. The first step in this is to work out the proportion of the t distribution that is higher than our observed t-value. Because we are running a two-tailed test (we are examining whether the true difference in population means is 0 or not equal to 0), we need to double that proportion to get our p-value.
![](img/tt6.png)
The image above helps to explain how we'd calculate the p-value. Because it's a two-tailed test, we need to calculate the proportion of the distribution in the red area - this is the area that is greater than $t=2.115$ and less than $t=-2.115$. We can use the `pt()` function in R to calculate this - remember that for this example, our degrees of freedom are 31:
```{r}
1 - pt(2.115, df=31)
```
This tells us that the area beyond $t=2.115$ is 0.021. Therefore to get our p-value we double this:
```{r}
(1 - pt(2.115, df=31)) * 2
```
Our p-value is $p = 0.043$.
** One-tailed test **
If we had predicted beforehand that Anastaia's students would score more highly on the exam than Bernadette's then we could perform a one-tailed test. The hypotheses in this situation would be:
$H_{0}: \mu_A \le \mu_A$
$H_{1}: \mu_A > \mu_A$
All of the steps for calculating the observed $t$-value would be the same as above. The only difference is when calculating the p-value, we only need to consider the area under the curve beyond $t=2.115$. Therefore the p-value for this one-tailed test is $p = 0.021$.
<br><br>
## Confidence Interval for Difference in Means
When we take a sample of two independent groups, we are able to directly calculate the observed difference in sample means $\overline{x}_A - \overline{x}_B$. What we are usually interested in is whether this observed difference is meaningfully different from 0. One way to gain more insight into whether this might be true or not is to generate a 95% confidence interval around our observed sample difference $\overline{x}_A - \overline{x}_B$. If 0 is not inside our confidence interval, then this is pretty good evidence that the true difference in population means $\mu_A - \mu_B$ between the two groups is not 0, and therefore there is a difference in population means.
As with all confidence intervals, the longer explanation as to what a 95% confidence interval really is, is a bit more long winded. Technically, this 95% confidence intervals means that if we were to take many samples of A and many samples of B, and calculate the difference and confidence intervals for all of them, in 95% of these confidence intervals we would have captured the true difference in population means $\mu_A - \mu_B$.
Let's illustrate with a small example, and then we'll turn to our TA data.
<br>
*Example 1*
A researcher compares the reaction times of two groups on a motor test. Individuals are different (independent) in each group. GroupA took a stimulant prior to the test. GroupB is the control group.
```{r}
groupA <- c(5.5, 5.1, 3.5, 5.1, 4.6, 4.6, 5.9, 4.0, 3.1, 3.8)
mean(groupA) # 4.52
sd(groupA) # 0.91
groupB <- c(5.7, 5.3, 5.9, 5.0, 5.0, 4.3, 4.1, 5.9, 5.9, 5.8, 5.4, 5.2, 4.9, 5.5)
mean(groupB) # 5.28
sd(groupB) # 0.58
```
```{r}
# plot the data:
dd <- data.frame(values = c(groupA, groupB),
group = c(rep("A",10), rep("B", 14))
)
head(dd)
ggplot(dd, aes(x = group, y = values, fill = group)) +
geom_boxplot(alpha=.3) +
geom_jitter(width=.1, size=2) +
theme_classic() +
scale_fill_manual(values = c("firebrick", "dodgerblue"))
```
We can see from our data, that the observed difference in sample means between the two groups is $\overline{x}_A - \overline{x}_B = -0.759$
```{r}
mean(groupA) - mean(groupB)
```
Group B (the control group) is slower by 0.76 seconds on average than group A (the group that took the stimulant).
The first step in constructing a confidence interval around this observed difference in sample means, is to imagine that this observed difference in sample means came from a sampling distribution of difference in sample means. Our observed value was just one possible sample that we could have got from this sampling distribution.
This sampling distribution of differences in sample means, is $t$-shaped with degrees of freedom equal to $n-2$. We assume that our observed value of the difference in sample means is a good estimate of the true difference in population means. If we know the standard deviation of this sampling distribution, then we can create the 95% confidence interval around it using the formula:
$\Large CI_{95\%} = \overline{x}_A - \overline{x}_B \pm t \times \sigma_{\overline{x}_A - \overline{x}_B}$
As discussed in the previous sections (see \@ref(sampling-distribution-of-the-difference-in-sample-means) and \@ref(pooled-standard-deviation)) the standard deviation of the sampling distribution of differences in sample means, can be calculated using the formula:
$\Large \sigma_{\overline{x}_A - \overline{x}_B} = \hat{\sigma_{\rho}} \times \sqrt{\frac{1}{n_A} + \frac{1}{n_B}}$
where $\hat{\sigma_{\rho}}$ is the pooled estimate of the standard deviation between the two groups.
The below diagram illustrates how this formula determines the 95% confidence interval. Our margin of error is the value of $t$ for the $t$-distribution with the appropriate degrees of freedom that leaves 2.5% in each tail, and therefore 95% in the middle of the distribution. We multiply this value of $t$ by the standard deviation of the sampling distribution of the differences in sample means to get the margin of error.
![](img/tt7.png)
The first step is therefore to calculate the pooled estimate of the common standard deviation $\hat{\sigma_{\rho}}$ (see section \@ref(sampling-Distribution-of-the-difference-in-sample-means)). Using the method of calculating deviations from each group mean, we can find that $\hat{\sigma_{\rho}} = 0.73$
```{r}
difA2 <- (groupA - mean(groupA))^2
difB2 <- (groupB - mean(groupB))^2
sumsq <- sum(difA2) + sum(difB2)
n <- length(groupA) + length(groupB) #24
sd.pool <- sqrt(sumsq/(n-2))
sd.pool
```
Putting this value into the above formula, we can calculate the standard deviation of the sampling distribution of the differences in sample means to be $\sigma_{\overline{x}_A - \overline{x}_B} = 0.302$.
```{r}
sedm1 <- sd.pool * sqrt( (1/length(groupA)) + (1/length(groupB)))
sedm1
```
So now we have the estimated mean $\overline{x}_A - \overline{x}_B$ and the standard deviation $\sigma_{\overline{x}_A - \overline{x}_B}$ of our sampling distribution of differences in sample means. Because our sampling distribution approximates to a $t$-distribution of degrees of freedom = $n-2$, we calculate the value of $t$ which leaves 2.5% in the tails using the `qt()` function in R.
```{r}
n <- length(groupA) + length(groupB)
tval <- qt(.975, df = n-2)
tval
```
Using this value, we can calculate the margin of error, and the lower and upper bounds of the confidence interval:
```{r}
dm <- mean(groupA) - mean(groupB)
dm
tval*sedm1
dm + (tval*sedm1) # upper bound = -0.13
dm - (tval*sedm1) # lower bound = -1.39
```
So the confidence interval is equal to: $CI_{95\%} = -0.76 \pm 0.63$ or $CI_{95\%} = -0.76[-0.13, -1.39]$. This shows us that the true difference in population means is unlikely to include 0, so we can conclude that there is likely a true difference in population means between the two groups.
The above is the 'by hand' way to calculating the confidence interval, that explains the theory behind it. The quickest way is to use the R function `t.test()`. Inside the brackets, you include the two groups of data, and use `var.equal=T`. This last argument ensures that you are assuming that the variances between the two populations that the samples come from are equal. The `$conf.int` bit on the end just gives us the confidence intervals:
```{r}
t.test(groupA, groupB, var.equal = T)$conf.int
```
<br>
*Example 2*
Let's look at this with a second example using the `anastasia` and `bernadette` data.
First, we get the value of $\overline{x}_A - \overline{x}_B$, which is our observed difference in sample means. This is what we assume the mean of the sampling distribution of differences in sample means is.
```{r}
meandif <- mean(anastasia) - mean(bernadette) # 5.48
meandif # this is our observed difference in sample means
```
We find that $\overline{x}_A - \overline{x}_B=5.48$
Previously in section \@ref(theory-behind-student's-t-test) we calculated the standard deviation of this sampling distribution to be $\sigma_{\overline{x}_A - \overline{x}_B} = 2.59$. We saved this earlier as `sedm`.
```{r}
sedm
```
To calculate our margin of error, we need to multiply $\sigma_{\overline{x}_A - \overline{x}_B}$ by the value of $t$ that leaves 2.5% in each tail for a $t$-distribution with $n-2$ degrees of freedom:
```{r}
tval <- qt(.975, df = length(anastasia) + length(bernadette) -2)
tval #2.04
```
We can now calculate the confidence intervals:
```{r}
tval*sedm
meandif + (tval*sedm) # 10.76
meandif - (tval*sedm) # 0.20
```
So the 95% confidence interval is equal to: $CI_{95\%} = 5.48 \pm 5.28$ or $CI_{95\%} = 5.48[0.20, 10.76]$. These CIs suggest that 0 is not likely to be the true difference in population means, therefore it is plausible that the population of students that have Anastasia as a TA score more highly on their exams than the population of students that have Bernadette as a TA.
We could have checked this using `ttest()`:
```{r}
t.test(anastasia, bernadette, var.equal = T)$conf.int
```
Finally, we could also plot confidence intervals like this:
```{r}
## plotting confidence intervals
dci <- data.frame(group = "",
mean = meandif,
lower = meandif - (tval*sedm),
upper = meandif + (tval*sedm)
)
ggplot(dci, aes(x=group, y=mean, ymax=upper, ymin=lower)) +
geom_errorbar(width=0.2, size=1, color="blue") +
geom_point(size=4, shape=21, fill="white") +
theme_minimal() +
coord_flip() +
xlab("") +
ylab("Estimate of Difference in Sample Means")
```
## Conducting the Student t-test in R
The function we need to conduct a Student's t-test in R is `t.test()`.
For instance, we want to test whether there is a difference in population means between the `anastasia` and `bernadette` samples. Here is the data visualized:
```{r}
# boxplot
ggplot(d, aes(x = group, y = values, fill = group)) +
geom_boxplot(alpha=.3, outlier.shape = NA) +
geom_jitter(width=.1, size=2) +
theme_classic() +
scale_fill_manual(values = c("firebrick", "dodgerblue"))
```
You can do the Student's t-test either from data stored in vectors, or in dataframes.
Here's how to do it for data stored in vectors. The first two arguments should be the names of the two independent samples. The final argument of `var.equal = T` tells R to do a Student's t-test by assuming that variances are equal between the two groups.
```{r}
t.test(anastasia, bernadette, var.equal = T)
```
As you can see from the output, the default Student's t-test is to do a 2-tailed test. In this output you are given the observed $t$-value, the degrees of freedom and the p-value. Also given are the sample means of each sample, as well as a 95% confidence interval of the true difference in population means (see section \@ref(confidence-interval-for-difference-in-means) for more on this confidence interval).
It's also possible to use `t-test` with data in long format in dataframes. Here is our data in long data format (we used this to make the boxplot):
```{r}
head(d)
tail(d)
```
In this format, we use `t.test()` and use the tilde `~` like this:
```{r}
t.test(values ~ group, data=d, var.equal = T)
```
As you can see, this gives the exact same output as using data stored in vectors.
To perform a one-tailed t-test, you need to add the argument `alternative = "greater"` or `alternative = "less"` as appropriate for your hypothesis. So, if you had hypothesized Anastasia's students came from a population with a greater population mean than the population that Bernadette's you would use `alternative = "greater"`:
```{r}
t.test(anastasia, bernadette, var.equal = T, alternative = "greater")
```
You could also do the following if your data are in long format:
```{r}
t.test(values ~ group, data=d, var.equal = T, alternative = "greater")
```
Notice that the observed $t$-value is the same as are the degrees of freedom compared to the two-tailed t-test. The p-value has actually halved. The confidence intervals also changed in the output, but you should use the confidence intervals from the two-tailed version of the test.
<br><br>
## Assumptions of the Independent t-test
The Student's t-test has two important assumptions that should be checked before you can fully be confident in the results of your statistical test.
<br>
**Independence fo Data**
As the name suggests, the data in each sample should be independent of each other. That is, individuals in each sample must be different - no individual should be in both groups. Also, subjects in one sample should not influence subjects in the other sample. e.g. If students who were in the Anastasia group studied with students who were in the Bernadette group, then the groups are no longer independent.
**Normality**
Firstly, the test assumes that both samples comes from populations that are normally distributed. We can test this by examining whether each sample is approximately normally distributed. Two options for doing this are to run a Shapiro-Wilk test, or make a QQ plot. Both test whether the distribution of data in your sample follow the normal distribution shape.
The Shapiro-Wilk test is run using `shapiro.test()`
```{r}
shapiro.test(anastasia)
shapiro.test(bernadette)
```
Because the p-values of these tests are both $p>.05$, we do not have sufficient evidence to suggest that our data are not approximately normal. In other words, we can assume that our data are approximately normal.
To make a QQ plot, we use `qnorm()` followed by `qqline()`. What we are looking for here is for our data points to roughly stick to the diagonal line. This would mean that our data values are approximately in line with what we'd expect for a normal distribution:
```{r}
qqnorm(anastasia)
qqline(anastasia, col = "steelblue", lwd = 2) # looks ok
qqnorm(bernadette)
qqline(bernadette, col = "steelblue", lwd = 2) # looks ok
```
In both of our plots, the data points are roughly against the line, which is good evidence that our data are normally distributed. Having some variability is fine, especially with datapoints at the tail of the x-axes.
**Homogeneity of Variance**
Another assumption of the Student's t-test is that we have homogeneity of variance between the populations that our samples come from. We assume this when we calculate the pooled standard deviation which helps us calculate the standard deviation of the sampling distribution.
We can examine the standard deviations of each group with `sd()` but this alone does not tell us if they are similar enough to qualify for having equality of variance:
```{r}
sd(anastasia)
sd(bernadette)
```
There is a formal test you can to to test for the equality of variance. This test is called a Levene's test. To do it, we use the `leveneTest()` function from the `car` library. To use it, you need your data in long format:
```{r, message=F,warning=F}
library(car)
leveneTest(y = d$values, group = d$group)
```
A p-value of $p>.05$ indicates that there is not sufficient evidence to suggest that the groups have different variances. In other words, we can assume that their variances are equal and we are ok to do a Student's t-test.
<br><br>
## Welch's t-test