-
Notifications
You must be signed in to change notification settings - Fork 0
/
Covariation_monophthongs_analysis.Rmd
3939 lines (3059 loc) · 192 KB
/
Covariation_monophthongs_analysis.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
---
title: "Systematic co-variation of monophthongs across speakers of New Zealand English"
subtitle: "Supplementary materials: _Analysis script_"
author: "James Brand<sup>1</sup>, Jen Hay<sup>1,2</sup>, Lynn Clark<sup>1,2</sup>, Kevin Watson<sup>1,2</sup> & Márton Sóskuthy<sup>3</sup><br><br/> <sup>1</sup>New Zealand Institute for Language, Brain and Behaviour, Univeristy of Canterbury, NZ<br> <sup>2</sup>Department of Linguistics, Univeristy of Canterbury, NZ<br><sup>3</sup>Department of Linguistics, The University of British Columbia, CA<br/><br/>Corresponding author: James Brand<br/>Email: james.brand.ac@gmail.com<br/>Website: https://jamesbrandscience.github.io"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
theme: cosmo
toc: true
toc_float: true
collapsed: false
df_print: paged
code_folding: show
self_contained: false
lib_dir: libs
---
<!-- set the colour scheme of the html file -->
<style>
.list-group-item.active, .list-group-item.active:focus, .list-group-item.active:hover {
background-color: #95A044;
}
</style>
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message=FALSE, dpi=400)
```
# Document outline
This document provides the code used in the analyses of the Brand, Hay, Clark, Watson and Sóskuthy (2020) manuscript, submitted to the Journal of Phonetics. It contains the various analysis steps reported in the paper, as well as additional analyses that the authors completed but were not considered central to the manuscript's core research questions, they are included here in case readers are interested.
Whilst every attempt has been made to make the code transparent, clear and comprehensible to all readers, regardless of your proficiency with using R or the statistical procedures applied in the analyses, if there are questions/queries/issues that do arise, please do contact the corresponding author (contact details at the top of the document).
Note that in the project repository, large and computationally expensive processes, such as the GAMM modelling, have been pre-run and important data stored in the `Data` folder. This has been done to ensure the compilation of this file is achieved relatively quickly and can be hosted online (i.e. via GitHub and OSF), in addition to allowing others to have quick access to all the required data. These steps are included in this file and can be run on your own computer to reproduce all the original files. When pre-run steps have been carried out, they are identifiable in the `.Rmd` file by the chunks having an `eval=FALSE` argument. If you are running these chunks, please ensure you have sufficient memory avialable (I require 13.18GB to store the `Analysis` folder, when all models are saved).
```{r}
cat(paste0("Start time:\n", format(Sys.time(), "%d %B %Y, %r")))
start_time <- Sys.time()
```
# Analysis steps
The document covers a number of steps that we completed, all of which can be reproduced by using the code and data in the project repository (https://github.com/nzilbb/Covariation_monophthongs_NZE). In order to orientate the reader, we provide a brief written outline of what the steps are.
1. Load in the data and provide summaries of the how it is structured.
2. Apply a new normalisation procedure (Lobanov 2.0) to the formant measurements.
3. Run a series of GAMMs that model the normalised values (per formant and per vowel), with fixed effects of speaker year of birth, gender and speech rate. These models will then be used to extract the by-speaker random intercepts, which we use as estimates of how innovative a speaker's realisations of each vowel are in terms of F1/F2, whilst keeping the fixed effects constant.
4. Run a principal components analysis (PCA) on the speaker intercepts data. Then inspect the eigen values of each of the principal components (PCs), this will allow us to determine which PCs account for sufficient variance to be meaningfully interpreted.
5. Extract the PCA scores from the PCs, which give each individual speaker a value for each PC, the more extreme (i.e. high or low) this value, the more the speaker contributes to the PC's formation. This will allow us to identify which speakers are representative of the PCs.
6. Assess if any of the PCs can be explained by the fixed-effects from the GAMM fitting procedure, i.e. is there a relationship between the PCA scores and factors such as year of birth or gender. We will provide examples of speaker vowel spaces to assist in the interpreation of the PCs in terms of F1/F2 space (the Shiny app allows for exploration of all speakers, so we recommend that as the optimal tool for understanding speaker variation https://onze.shinyapps.io/Covariation_shiny/).
7. Following on from the previous inspection of the variables, our interpretation for how they co-vary together within a more theoretical framework (as explained in the paper), was driven by our understanding of the directions of change in F1/F2. To demonstrate this we will run additional GAMMs predicting F1/F2 by the PCA scores. Then visualise how these changes map onto change in New Zealand English.
# Pre-requisites
**Purpose: Install libraries and load data**
In order for the code in this document to work, the following packages are required to be installed and loaded into your R session. If you do not have any of the packages installed, you can run `install.packages("PACKAGE NAME")` which should resolve any warning messages you might get (change "PACKAGE NAME" to the required package name, e.g. `install.packages("tidyverse")`).
A large portion of the code in this document is written in a _tidy_ way, this means that it (tries to) always use the `tidyverse` functions when possible, if you are new to using R or are more familiar with R's `base` packages, see [http://tidyverse.tidyverse.org/](http://tidyverse.tidyverse.org/) for a full reference guide.
Similarly, if there are any functions that you are not familiar with/would like more information on (or the arguments to those functions), simply press `F1` whilst your cursor is clicked anywhere on the name of the function, this will bring up the help page in RStudio (note this will only work if you are using the `.rmd` version of this file and not the `.html`).
For more general information on R Markdown documents and how they work see [https://rmarkdown.rstudio.com/index.html](https://rmarkdown.rstudio.com/index.html)
##Libraries
The following libraries are required for the document to be run.
```{r}
library(lme4) #mixed-effects models
library(rms) #fitting restricted cubic splines
library(cowplot) #plotting functions
library(tidyverse) #lots of things
library(kableExtra) #outputting nice tables
library(factoextra) #pca related things
library(ggrepel) #more plotting things
library(gganimate) #animation plotting
library(lmerTest) #p values from lmer models
library(DT) #interactive data tables
library(mgcv) #gamms
library(itsadug) #additional gamm things
library(scales) #rescale functions
library(gifski) #needed to generate gif
library(circlize) #chord diagram
library(PerformanceAnalytics) #correlation figure
#this is important for reproduction of any stochastic computations
set.seed(123)
#check information about R session, this will give details of the R setup on the authors computer at the time of running. If any of the outputs are not reproduced as in the html file produced from this markdown document (see repository), there may be differences in the package versions or setup on your computer. You can update packages by running utils::update.packages()
sessionInfo()
```
# Data
**Purpose: Understand the structure of the dataset**
All data has been made available to reproduce the results, the data file should be located in a folder called `data` within the folder/directory this file is saved in. We will store the data as an R data frame called `vowels_all`. Note the data is saved as a `.rds` file, this is essentially the same as a normal `.csv` file, but is more efficient when working in R. If you wish to reuse the data in a different format, it is recommended that you load in the data and then export it to your preferred format, e.g. using the `write.csv()` function for `.csv` files.
```{r}
#load in the data
vowels_all <- readRDS("Data/ONZE_vowels_filtered_anon.rds")
```
We can inspect the data in different ways, to ensure that the correct file has been loaded and for general understanding of how the data is structured.
## Variables
Let's inspect the variables...
We should have **`r length(names(vowels_all))`** variables.
Definitions of each variable are given below (factors are represented as *fct* with the number of unique levels also provided e.g. *fct (481)* represents a factor with 2 unique values, numeric variables are represented as *num*, with the smallest and largest values provided, e.g. *num (1864-1982)*):
```{r echo=FALSE}
data.frame(
Variable = c("Speaker",
"Transcript",
"Corpus",
"Gender",
"participant_year_of_birth",
"Word",
"Vowel",
"F1_50",
"F2_50",
"Speech_rate"),
Description = c(
"The speaker ID (format: corpus_gender_distinctnumber, e.g. IA_f_001",
"The transcript number of the speaker, e.g. IA_f_001-01.trs",
"The sub-corpus the data comes from, i.e. either MU, IA, Darfield or CC",
"The gender of the speaker, i.e. either F for female or M for male",
"The year the participant was born in e.g. 1864",
"The word form of the token, this is anonymised (format: word_distinctnumber, e.g. word_00002",
"The vowel of the token, using Well’s notation, e.g. FLEECE",
"The raw F1 of the vowel in Hz, taken at the mid-point, e.g. 500",
"The raw F2 of the vowel in Hz, taken at the mid-point, e.g. 1500",
"The speech rate in syllbales per second for the transcript, e.g. 1.7929"),
Class = c(
paste0("fct (", vowels_all %>% select(Speaker) %>% n_distinct(), ")"),
paste0("fct (", vowels_all %>% select(Transcript) %>% n_distinct(), ")"),
paste0("fct (", vowels_all %>% select(Corpus) %>% n_distinct(), ")"),
paste0("fct (", vowels_all %>% select(Gender) %>% n_distinct(), ")"),
paste0("num (", vowels_all %>% select(participant_year_of_birth) %>% min(), "-", vowels_all %>% select(participant_year_of_birth) %>% max(), ")"),
paste0("fct (", vowels_all %>% select(Word) %>% n_distinct(), ")"),
paste0("fct (", vowels_all %>% select(Vowel) %>% n_distinct(), ")"),
paste0("num (", vowels_all %>% select(F1_50) %>% min(), "-", vowels_all %>% select(F1_50) %>% max(), ")"),
paste0("num (", vowels_all %>% select(F2_50) %>% min(), "-", vowels_all %>% select(F2_50) %>% max(), ")"),
paste0("num (", vowels_all %>% select(Speech_rate) %>% min(), "-", vowels_all %>% select(Speech_rate) %>% max(), ")")
)
) %>%
mutate(Variable = cell_spec(Variable, color = "#273746",
background = "#F2F3F4")) %>%
kable(escape = F) %>%
kable_styling(full_width = FALSE) %>%
column_spec(1) %>%
column_spec(2, width = "30em") %>%
column_spec(3, italic = TRUE)
```
Next, we can generate some summary information about the dataset.
### Token counts
There are 10 different vowels in the data, a summary of the number of tokens per vowel is given below.
Originally, we extracted 12 vowels, comprising the 10 summarised below, but also SCHWA and FOOT, these were removed during the data cleaning stage, SCHWA was removed as we are only analysing stressed tokens and the number of speakers with low N tokens for FOOT would have led to large loss in the number of speakers in the data.
```{r echo=FALSE}
vowels_all %>%
group_by(Vowel) %>% #make vowels the summary variable
summarise(`N Tokens` = n(), #get the n tokens per vowel
`%` = `N Tokens`/nrow(vowels_all)*100) %>% #get the percentage of tokens per vowel from the whole dataset
arrange((as.character(Vowel))) %>% #order the rows alphabetically by vowel
rbind((vowels_all %>% #add the total row values
summarise(Vowel = "Total",
`N Tokens` = n(),
`%` = 100))
) %>%
arrange(`N Tokens`) %>%
kable(digits = 1, align = c("l", "c", "c")) %>%
kable_styling(full_width = FALSE) %>%
row_spec(11, bold = TRUE, color = "black")
```
### Sub-corpora
The ONZE dataset comprises four different sub-corpora:
MU - Mobile Unit<br>
IA - Intermediate Archive<br>
CRS/Darfield - Canterbury Regional Survey<br>
CC - Canterbury Corpus<br>
Below is a summary of the demographic information for each of the sub-corpora.
```{r warning=FALSE, echo=FALSE}
#create data frame for sub-corpus summary
demographics1 <- vowels_all %>%
group_by(Corpus) %>% #group by sub-corpus
summarise(`N Tokens` = n(), #n tokens
`% Tokens` = `N Tokens`/nrow(vowels_all)*100, #n tokens as a percent
`N Speakers` = n_distinct(Speaker), #n speakers
`Year of Birth Range` = paste(min(participant_year_of_birth), #min year of birth
"-", #divide the 2 values
max(participant_year_of_birth))) %>%# max year of birth
arrange(factor(Corpus, levels = c("MU", "IA", "Darfield", "CC"))) #order the rows by sub-corpus birth range
#create new data frame for sub-corpus and gender summary
demographics2 <- vowels_all %>%
group_by(Corpus, Gender) %>% #group by sub-scorpus and gender
summarise(n = n_distinct(Speaker)) %>% #get n speakers
mutate(Gender = fct_recode(Gender, "Female" = "F", "Male" = "M")) %>% #rename the gender levels to be clearer
arrange(factor(Corpus, levels = c("MU", "IA", "Darfield", "CC"))) %>% #order the rows by sub-corpus birth range %>%
spread(Gender, n) #convert long format data to wide
#join the two data frames together
demographics <- inner_join(demographics1[,1:4], demographics2, by = "Corpus") %>%
inner_join(demographics1[,c(1, 5)], by = "Corpus")
#output the data as a table
demographics %>%
kable(digits = 2, align = c("l", "c", "c", "c", "c", "c", "c")) %>% #make table and round decimals to 1
kable_styling(full_width = FALSE) #add styling
#remove the unneeded demographics data frames
rm(demographics, demographics1, demographics2)
```
### Speakers
The distribution of speakers by gender is given in the histogram below.
```{r}
demographics_speakers <- vowels_all %>%
mutate(Gender = ifelse(Gender == "F", "Female", "Male")) %>%
select(Speaker, Gender, participant_year_of_birth) %>%
distinct() %>%
group_by(Gender) %>%
summarise(n = n())
#histogram of the speakers by year of birth and gender
demographic_speakers_plot <- vowels_all %>%
select(Speaker, Gender, participant_year_of_birth) %>%
distinct() %>%
mutate(Gender = ifelse(Gender == "F", "Female", "Male")) %>%
ggplot(aes(x = participant_year_of_birth, fill = Gender, colour = Gender)) +
geom_histogram(binwidth=1,
alpha = 0.8, colour = NA) +
geom_rug(alpha = 0.2) +
annotate("rect", xmin = 1860, xmax = 1895, ymin = 12, ymax = 23, fill = "white", colour = "black") +
scale_x_continuous(breaks = seq(1860, 1990, 15), name = "Speaker year of birth") +
scale_y_continuous(name = "Count") +
scale_fill_manual(values = c("black", "#7CAE00"), name = "Gender", guide = guide_legend(title.position = "top")) +
scale_color_manual(values = c("black", "#7CAE00"), name = "Gender", guide = guide_legend(title.position = "top")) +
annotate("text", x = 1860.5, y = 17.8, hjust = 0, label = "atop(bold(Demographics))", parse = TRUE) +
annotate("text", x = 1860.5, y = 15, hjust = 0, label = paste0("N female = ", demographics_speakers$n[1], "\nN male = ", demographics_speakers$n[2], "\nN total = ", sum(demographics_speakers$n), "\nyob range = ", min(vowels_all$participant_year_of_birth), ":", max(vowels_all$participant_year_of_birth))) +
# geom_text(data = vowels_all %>% filter(participant_year_of_birth > 1863 & participant_year_of_birth < 1983) %>% select(Speaker, Gender, participant_year_of_birth) %>% distinct() %>% group_by(Gender) %>% summarise(n = n()), aes(x = 1862, y = 17, label = paste0("N female = ", n[1], "\nN male = ", n[2], "\nN total = ", sum(n), "\nyob range: ", min(vowels_all$participant_year_of_birth), " - ", max(vowels_all$participant_year_of_birth))), hjust=0, inherit.aes = FALSE) +
theme_bw() +
theme(legend.position = c(0.052, 0.95),
legend.direction = "horizontal",
legend.title = element_text(face = "bold"),
legend.justification = c(0.052, 0.95),
legend.background = element_rect(fill=alpha('white', 0)),
axis.text = element_text(size = 14),
axis.title = element_text(size = 14))
demographic_speakers_plot
ggsave(plot = demographic_speakers_plot, filename = "Figures/demographics_speakers_plot.png", width = 7, height = 4.5, dpi = 400)
```
Below we provide summary information about each of the speakers token counts per vowel. This table comprises all speakers in the dataset and can be ordered and searched like a spreadsheet.
```{r echo=FALSE}
vowels_all %>%
group_by(Speaker, Vowel) %>% #group by speaker and vowel
summarise(n = n()) %>% #get the token counts for each speaker and vowel
spread(Vowel, n) %>% #go from long to wide data format
ungroup() %>%
mutate(N_tokens = rowSums(.[-1]),
Overall_percent = round(as.numeric((N_tokens/sum(N_tokens))*100), 3)) %>%
datatable(options = list(scrollX = TRUE))
```
# Normalisation
We will now normalise the raw F1 and F2 values.
Here, we introduce an adapted version of the Lobanov (1971) normalisation method, which we refer to as `Lobanov 2.0`. Explanations of the formula for each of the methods (Lobanov and Lobanov 2.0) are given below. Please refer to the paper for reasons why this adapted version was preferred to Lobanov's original normalisation method.
## Lobanov formula:
$$
\begin{equation}
F_{lobanov_i} = \frac{(F_{raw_i}-\mu_{raw_i})}{\sigma_{raw_i}}
\end{equation}
$$
- $i$ = either F1 or F2
- $F_{lobanov_i}$ = the normalised value in $i$
- $F_{raw_i}$ = the raw formant measurement value in $i$
- $\mu_{raw_i}$ = the mean formant value calculated across all raw values in $i$
- $\sigma_{raw_i}$ = the standard deviation calculated across all raw values in $i$
In plain English, the formula subtracts the mean formant value of a speaker from the raw individual formant value, then divides that by the standard deviation of the formant values.
e.g. if a speaker has a raw F1 of 400hz, a mean F1 of 500hz and a standard deviation of 70hz, this would give a Lobanov normalised value of (400-500)/70 = -1.43.
## Lobanov 2.0 formula:
$$
\begin{equation}
F_{lobanov2.0_i} = \frac{(F_{raw_i}-\mu_{(\mu_{vowel_1},\cdots,\mu_{vowel_n})})}{\sigma_{(\mu_{vowel_1},\cdots,\mu_{vowel_n})}}
\end{equation}
$$
- $i$ = either F1 or F2
- $F_{lobanov2.0_i}$ = the normalised value in $i$
- $F_{raw_i}$ = the raw formant measurement value in $i$
- $\mu_{(\mu_{vowel_1},\cdots,\mu_{vowel_n})}$ = the mean taken from the mean formant value calculated per vowel in $i$
- $\sigma_{(\mu_{vowel_1},\cdots,\mu_{vowel_n})}$ = the standard deviation taken from the mean formant value calculated per vowel in $i$
In plain English, the formula subtracts the mean of means formant value of a speaker (calculated as the mean of means, where a mean for each vowel is calculated, then the mean taken of those means) from the raw individual formant value, then divides that by the standard deviation of the mean of mean values.
e.g. if a speaker has a raw F1 of 400hz, a mean of means F1 of 550hz and a standard deviation (for the mean of means) of 70hz, this would give a Lobanov 2.0 normalised value of (400-550)/70 = -2.14.
## Implementation
The primary difference between the formula for this adapted version and Lobanov's original formula, is that each of the vowels has a mean formant value calculated, then a mean of those means is taken as the mean in the formula. The motivation for doing this is that the data we are normalising contains speakers with varying numbers of tokens across the different vowels. Lobanov's method is suited (and designed) based on balanced data, where an equal number of tokens per vowel are normalised.
When normalising with unbalanced numbers of tokens per vowel, the calculation of $\mu_{raw_i}$ (the mean of all the raw formant values), can be skewed by tokens that have a much larger count in a certain vowel.
Therefore, we first calculate means for each of the individual vowels (per speaker, per formant), then calculate the mean based on those means. This approach allows for tokens in vowel categories to be weighted equally regardless of how many tokens there are, making the normalisation more reliable for this type of dataset.
For visualisation purposes, we plot the normalised values for F1 and F2 against each other in the plots below (Lobanov 2.0 is on the x axis and Lobanov on the y axis, with coloured lines representing each speaker, the black line represents where the values would be if they were equal, i.e. if Lobanov 2.0 = Lobanov)
```{r}
#standard Lobanov normalisation - calculate means across all vowels per speaker
summary_vowels_all_lobanov <- vowels_all %>%
group_by(Speaker) %>%
dplyr::summarise(mean_F1_lobanov = mean(F1_50),
mean_F2_lobanov = mean(F2_50),
sd_F1_lobanov = sd(F1_50),
sd_F2_lobanov = sd(F2_50),
token_count = n())
#Lobanov 2.0 - calculate means per vowel and per speaker
summary_vowels_all <- vowels_all %>%
group_by(Speaker, Vowel) %>%
dplyr::summarise(mean_F1 = mean(F1_50),
mean_F2 = mean(F2_50),
sd_F1 = sd(F1_50),
sd_F2 = sd(F2_50),
token_count_vowel = n())
#get the mean_of_means and sd_of_means from the the speaker_summaries, this will give each speaker a mean caculated from the means across all vowels, as well as the standard deviation of the means
summary_mean_of_means <- summary_vowels_all %>%
group_by(Speaker) %>%
dplyr::summarise(mean_of_means_F1 = mean(mean_F1),
mean_of_means_F2 = mean(mean_F2),
sd_of_means_F1 = sd(mean_F1),
sd_of_means_F2 = sd(mean_F2)
)
#combine these values with the full raw dataset, then use these values to normalise the data with both the Lobanov and the Lobanov 2.0 method
vowels_all <- vowels_all %>%
#add in the data
left_join(., summary_mean_of_means) %>%
left_join(., summary_vowels_all[, c("Speaker", "Vowel", "token_count_vowel")]) %>%
left_join(., summary_vowels_all_lobanov) %>%
#normalise the raw F1 and F2 values with Lobanov
mutate(F1_lobanov = (F1_50 - mean_F1_lobanov)/sd_F1_lobanov,
F2_lobanov = (F2_50 - mean_F2_lobanov)/sd_F2_lobanov,
#normalise with Lobanov 2.0
F1_lobanov_2.0 = (F1_50 - mean_of_means_F1)/sd_of_means_F1,
F2_lobanov_2.0 = (F2_50 - mean_of_means_F2)/sd_of_means_F2) %>%
#remove the variables that are not required
dplyr::select(-(mean_of_means_F1:sd_of_means_F2), -(mean_F1_lobanov:sd_F2_lobanov))
#remove the previous summary data frames
rm(summary_vowels_all_lobanov, summary_vowels_all, summary_mean_of_means)
#inspect the relationship between the two normalised values
F1 <- vowels_all %>%
ggplot(aes(x = F1_lobanov_2.0, y = F1_lobanov, group = Speaker, colour = Speaker)) +
geom_smooth(method = "lm", size = 0.1, show.legend = FALSE) +
geom_abline(slope=1, intercept=0) +
theme_bw()
vowels_all %>%
group_by(Speaker) %>%
do(mod = lm(F1_lobanov ~ F1_lobanov_2.0, data = .)) %>%
mutate(Slope = summary(mod)$coeff[2]) %>%
select(-mod) %>%
# summarise(cor = cor(F1_lobanov_2.0, F1_lobanov)) %>%
# as.data.frame() %>%
# ungroup() %>%
# pivot_wider(names_from = Vowel, values_from = cor) %>%
View()
vowels_all %>%
filter(Speaker %in% c("MU_f_593", "CC_m_103")) %>%
rowid_to_column() %>%
pivot_longer(c(F1_50:F2_50, F1_lobanov:F2_lobanov_2.0)) %>%
mutate(variable = str_sub(name, 1, 2)) %>%
mutate(version = ifelse(str_detect(name, "50"), "Hz",
ifelse(str_detect(name, "2.0"), "Lobanov 2.0", "Lobanov"))) %>%
select(-name) %>%
pivot_wider(names_from = variable, values_from = value) %>%
# filter(version != "Hz") %>%
filter(version == "Hz") %>%
ggplot(aes(x = F2, y = F1, colour = Vowel, linetype = Speaker, shape = Speaker)) +
# geom_point(size = 0.5, alpha = 0.2) +
stat_ellipse(level = 0.67) +
scale_x_reverse(position = "top") +
scale_y_reverse(position = "right") +
facet_wrap(~version) +
theme_bw() +
theme(legend.position = "none")
vowels_all %>%
ggplot(aes(x = F2_lobanov_2.0, y = F2_lobanov, colour = Speaker)) +
geom_smooth(method = "lm", size = 0.1, show.legend = FALSE) +
geom_abline(slope=1, intercept=0) +
theme_bw()
```
Make a plot for Figure 1 in the manuscript, of speakers born between 1900-1930. This will show the normalised vowel space and individual speaker means for the 10 vowels. There will also be ellipses to show the variation in the vowel productions and the black points indicate the individual vowel means, calculated across the sample of speakers.
```{r}
#calculate individual speaker means for each vowel
vowel_means_example <- vowels_all %>%
filter(participant_year_of_birth %in% c(1900:1930)) %>%
group_by(Speaker, Vowel, Gender, participant_year_of_birth) %>%
summarise(mean_F1 = mean(F1_lobanov_2.0),
mean_F2 = mean(F2_lobanov_2.0))
vowel_means_example1 <- vowels_all %>%
filter(participant_year_of_birth %in% c(1900:1930)) %>%
group_by(Vowel) %>%
summarise(mean_F1 = mean(F1_lobanov_2.0),
mean_F2 = mean(F2_lobanov_2.0))
vowel_means_example_plot <- vowel_means_example %>%
ggplot(aes(x = mean_F2, y = mean_F1, colour = Vowel)) +
geom_point() +
stat_ellipse(level = 0.67) +
geom_label(data = vowel_means_example1, aes(label = Vowel)) +
geom_point(data = vowel_means_example %>% filter(Speaker == "CC_f_326")) +
geom_point(data = vowel_means_example %>% filter(Speaker == "CC_f_326"), colour = "black", size = 3, shape = 5, stroke = 2) +
scale_x_reverse(name = "F2 (Normalised)", position = "top") +
scale_y_reverse(name = "F1 (Normalised)", position = "right") +
theme_bw() +
theme(legend.position = "none")
vowel_means_example_plot
ggsave(plot = vowel_means_example_plot, filename = "Figures/vowel_means_example.png", dpi = 400)
```
# GAMM modelling
In order to analyse co-variation in the dataset, we first must extract a measure of how the speakers vocalic variables differ from one another. To achieve this, we first run a series of Generalised Additive Mixed Models (GAMMs), from which we can extract the by-speaker random intercepts. This is done using the `mgcv` and `itsadug` packages, if you are unfamiliar with this form of analysis, see (Winter and Wieling, (2016))[https://academic.oup.com/jole/article/1/1/7/2281883] or (Sóskuthy, (2017))[https://arxiv.org/abs/1703.05339], for further information about why we chose the by-speaker intercepts, please refer to the manuscript or see [Drager and Hay (2012)](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/6B661A6226E015A613AB22616C9C2300/S0954394512000014a.pdf/exploiting_random_intercepts_two_case_studies_in_sociophonetics.pdf)
In total there will be 20 separate models (10 vowels x 2 formants) that will be fitted, each of which we will extract the random intercepts from the random effect of `Speaker`, as well as the model summary.
## Fitting procedure
Each of the models will use the data from one of the 10 vowels (in the `Vowel` variable) and will have either the `F1_lobanov_2.0` or the `F2_lobanov_2.0` variable as the dependent/predicted measure.
All models will be fit uniformly, i.e. with the same fixed and random effects structures.
The fixed effects are:
- An interaction between `participant_year_of_birth` and `Gender`
- `participant_year_of_birth`
- `Gender`
- `Speech_rate`
The random effects are:
- `Speaker`
- `Word`
The `participant_year_of_birth` variable is modeled with a smooth term with 10 knots, this is to account for the non-linear 'wiggliness' of the effect.
To run the models in an efficient way and store the by-speaker intercepts, we use a `for` loop to iterate through each of the vowels, extracting the intercepts from each model and adding them to a data frame.
A for loop works by iterating over each value in a series, here we will loop through each value in our `Vowels` variable and extract the relevant information.
e.g the for loop will start with `DRESS`, run the GAMM for F1, extract the by-speaker intercepts from that model, it will then run the GAMM for F2, extract the speaker intercepts from this model, then add the 2 sets of intercepts to a data frame (`gam_intercepts.tmp`). The loop will then move on to the next vowel, `FLEECE` and do exactly the same process. The loop will finish once all vowels have been 'looped' through.
This will result in a data frame comprising:
- 494 rows (one row per speaker)
- 1 column identifying the speaker name
- 20 additional columns identifying the variable being modeled (e.g. F1_DRESS), the numeric values here represent the by-speaker intercepts from that variable's model
**Note, this process takes several hours (six and half hours on my machine) to complete**. The output has been stored in files in the `GAMM_output` folder, for quick reference. Please see those files or load them in to your R session for the rest of the analysis if you do not run the following code chunk.
The intercepts are saved as `gamm_intercepts.csv`, the model summaries can be found in the `model_summaries` sub-folder, where each model summary is stored as a `.rds` file, e.g. `gam_summary_F1_DRESS.rds` contains the model summary for F1_DRESS.
```{r}
#update the Gender variable to allow for conrast coding
vowels_all$Gender <- as.ordered(vowels_all$Gender)
contrasts(vowels_all$Gender) <- "contr.treatment"
vowels_all <- vowels_all %>%
arrange(as.character(Speaker))
```
```{r eval=FALSE}
#create a data frame to store the intercepts from the models, this will initially contain just the speaker names
gam_intercepts.tmp <- vowels_all %>%
dplyr::select(Speaker) %>%
distinct()
#loop through the vowels
cat(paste0("Start time:\n", format(Sys.time(), "%d %B %Y, %r\n")))
for (i in levels(factor(vowels_all$Vowel))) {
#F1 modelling
#run the mixed-effects model on the vowel, i.e. if i = FLEECE this will model F1 for FLEECE
gam.F1 <- bam(F1_lobanov_2.0 ~
s(participant_year_of_birth, k=10, bs="ad", by=Gender) +
s(participant_year_of_birth, k=10, bs="ad") +
Gender +
s(Speech_rate) +
s(Speaker, bs="re") +
s(Word, bs="re"),
data=vowels_all %>% filter(Vowel == i),
discrete=T, nthreads=2)
#extract the speaker intercepts from the model and store them in a temporary data frame
gam.F1.intercepts.tmp <- as.data.frame(get_random(gam.F1)$`s(Speaker)`)
#assign the model to an object
assign(paste0("gam_F1_", i), gam.F1)
#save the model summary
saveRDS(gam.F1, file = paste0("/Users/james/Documents/GitHub/model_summaries/gam_F1_", i, ".rds"))
cat(paste0("F1_", i, ": ", format(Sys.time(), "%d %B %Y, %r"), " ✅\n")) #print the vowel the loop is up to for F1, as well as the start time for the model
#F2 modelling
#run the mixed-effects model on the vowel, i.e. if i = FLEECE this will model F2 for FLEECE
gam.F2 <- bam(F2_lobanov_2.0 ~
s(participant_year_of_birth, k=10, bs="ad", by=Gender) +
s(participant_year_of_birth, k=10, bs="ad") +
Gender +
s(Speech_rate) +
s(Speaker, bs="re") +
s(Word, bs="re"),
data=vowels_all %>% filter(Vowel == i),
discrete=T, nthreads=2)
#extract the speaker intercepts again, storing them in a separate data frame
gam.F2.intercepts.tmp <- as.data.frame(get_random(gam.F2)$`s(Speaker)`)
#assign the model to an object
assign(paste0("gam_F2_", i), gam.F2)
#save the model summary
saveRDS(gam.F2, file = paste0("/Users/james/Documents/GitHub/model_summaries/gam_F2_", i, ".rds"))
#rename the variables so it clear which one has F1/F2, i.e. this will give F1_FLEECE, F2_FLEECE
names(gam.F1.intercepts.tmp) <- paste0("F1_", i)
names(gam.F2.intercepts.tmp) <- paste0("F2_", i)
#combine the intercepts for F1 and F2 and store them in the intercepts.tmp_stress data frame
gam_intercepts.tmp <- cbind(gam_intercepts.tmp, gam.F1.intercepts.tmp, gam.F2.intercepts.tmp)
cat(paste0("F2_", i, ": ", format(Sys.time(), "%d %B %Y, %r"), " ✅\n")) #print the vowel the loop is up to for F2 , as well as the start time for the model
}
#save the intercepts as a .csv file
write.csv(gam_intercepts.tmp, "Data/gam_intercepts_tmp_new.csv", row.names = FALSE)
```
## Read in pre-run model results
In order to save time running through the GAMM modelling chunk above, the results have been stored in the repository for quick loading. The below code will load the files in to your R session.
```{r}
#load in model intercepts
gam_intercepts.tmp <- read.csv("Data/gam_intercepts_tmp_new.csv")
```
```{r eval=FALSE}
#make vector containing all .rds filenames from model_summaries folder
model_summary_files = list.files(pattern="*.rds", path = "/Users/james/Documents/GitHub/model_summaries")
#load each of the files with for loop
for (i in model_summary_files) {
cat(paste0(i, ": ", format(Sys.time(), "%d %B %Y, %r"), " ✅\n"))
assign(gsub(".rds", "", i), readRDS(paste0("/Users/james/Documents/GitHub/model_summaries/", i)))
}
```
## Understanding the intercepts
In order to better understand these intercepts and how they represent each speaker's position in relation to the population, it can be helpful to visualise the speaker intercepts in relation to the vowel space.
We interpret the speaker intercepts in terms of how advanced the vowel productions are in relation to other speakers with similar fixed-effects - in other words, if a speaker has a **large positive intercept** from a model (with a fixed-effects structure as that used in our above modelling procedure), this would indicate that the speaker is producing formant values that are typically **larger** than other speakers **with similar fixed-effects values**, e.g. year of birth, gender etc. Likewise, if the intercept is **negative**, this would indicate that their F values are smaller, the closer the intercept is to **0**, the more typical the speaker is (taking into account the fixed-effects).
To demonstrate this, we will visualise the change in `F1` for three vowels, known to have undergone rapid change in New Zealand English (`TRAP`, `DRESS` and `KIT`). We will plot the participant year of birth on the x axis and normalised F1 on the y axis (reverse scaled to match normal vowel plot conventions). To highlight the change in the three vowels over time, we will also fit a smooth and plot the mean F1 values of each speaker for each of the vowels. Finally, we will highlight 4 speakers who all have intercepts that indicate that they are **advanced** in these vowel changes, i.e. have negative intercepts (smaller F1) for `TRAP` and `DRESS`, but positive intercepts (larger F1) for `KIT`.
The first chunk calculates mean F1 values / speaker and merges this data with the speaker intercepts from the GAMMs.
The second chunk extracts predictions from the GAMMs for plotting smooths over year of birth. (This code block produces plots that are not included in the RMarkdown output).
```{r eval=FALSE}
vowels_to_plot <- c("KIT", "DRESS", "TRAP")
pred_table <- function (Vowel) {
mod_name <- paste0("gam_F1_", Vowel)
return(cbind(Vowel,
plot_smooth(get(mod_name), view="participant_year_of_birth",
rm.ranef=T, rug=F, n.grid=119)$fv)
)
}
gamm_preds_to_plot <- lapply(vowels_to_plot, pred_table) %>%
do.call(rbind, .)
saveRDS(gamm_preds_to_plot, "Data/Models/gamm_preds_to_plot.rds")
```
```{r}
gamm_preds_to_plot <- readRDS("Data/Models/gamm_preds_to_plot.rds")
```
We now plot the data.
```{r fig.width=7, fig.height=5, dpi=300}
#make a long version of the intercepts
gam_intercepts.tmp_long <- gam_intercepts.tmp %>%
pivot_longer(F1_DRESS:F2_TRAP, names_to = "Vowel_formant", values_to = "Intercept") %>%
mutate(Formant = substr(Vowel_formant, 1, 2),
Vowel = substr(Vowel_formant, 4, max(nchar(Vowel_formant)))) %>%
left_join(vowels_all %>%
select(Speaker, participant_year_of_birth) %>% distinct()) %>%
left_join(gamm_preds_to_plot %>% mutate(Formant = "F1") %>% select(participant_year_of_birth, Vowel, Formant, fit, ll, ul))
speakers1 <- gam_intercepts.tmp_long %>%
filter(Vowel_formant %in% c("F1_KIT", "F1_DRESS", "F1_TRAP")) %>%
ungroup() %>%
arrange(participant_year_of_birth) %>%
filter(Speaker %in% c("MU_m_348", "IA_f_341", "CC_m_167", "CC_f_297")) %>%
mutate(letters = c(rep("A", 3), rep("B", 3), rep("C", 3), rep("D", 3)),
speakers1 = paste0(letters, " (", round(Intercept, 2), ")"))
F1_speaker_intercepts <- gam_intercepts.tmp_long %>%
filter(Vowel %in% c("KIT", "DRESS", "TRAP"),
Formant == "F1") %>% #choose the vowels
mutate(Vowel = factor(Vowel, levels = c("TRAP", "DRESS", "KIT"))) %>% #order the vowels
ggplot(aes(x = participant_year_of_birth, y = fit, colour = Vowel, fill = Vowel)) +
geom_point(aes(x = participant_year_of_birth, y = fit + Intercept), size = 1, alpha = 0.2) +
geom_line() +
geom_ribbon(aes(ymin=ll, ymax=ul), colour = NA, alpha=0.2) +
geom_point(data = speakers1 %>% mutate(fit = ifelse(speakers1 %in% c("D (-0.36)"), fit - 0.05, fit)), aes(x = participant_year_of_birth, y = fit + Intercept), size = 4) +
geom_label(data = speakers1 %>% mutate(fit = ifelse(speakers1 %in% c("B (0.23)"), fit - 0.1, fit), fit = ifelse(speakers1 %in% c("D (-0.36)"), fit - 0.1, fit)), aes(x = participant_year_of_birth - 1, y = fit + Intercept, label = speakers1), fill = "white", alpha = 0.5, hjust = 1, show.legend = FALSE) +
scale_y_reverse() +
scale_colour_manual(values=c("#E69F00", "#56B4E9", "#009E73")) +
scale_fill_manual(values=c("#E69F00", "#56B4E9", "#009E73")) +
xlab("Participant year of birth") + #x axis title
ylab("Normalised F1 (Lobanov 2.0)") + #y axis title
theme_bw() + #general aesthetics
theme(legend.position = c(0.8, 0.1), #legend position
legend.direction = "horizontal",
legend.background = element_rect(colour = "black"),
axis.text = element_text(size = 14), #text size
axis.title = element_text(face = "bold", size = 14), #axis text aesthetics
legend.title = element_blank(), #legend title text size
legend.text = element_text(size = 14)) #legend text size
F1_speaker_intercepts
ggsave(plot = F1_speaker_intercepts, filename = "Figures/F1_speaker_intercepts.png", width = 10, height = 5, dpi = 400)
#clean up
rm(speakers, speakers1, F1_speaker_intercepts)
```
## Visualisation of intercept correlations
Understanding how the intercepts may be correlated to each other is an important first step to how they relate to each other. However, simply using correlations to gain a full understanding of how the covariation is operating, may not be sufficient. We present below an initial outline of the correlations between the intercepts.
1. Checking the distribution of the intercepts
```{r}
gam_intercepts.tmp %>%
select(-1) %>%
pivot_longer(cols = 1:20, names_to = "variable", values_to = "intercept") %>%
ggplot(aes(x = intercept, y = ..density..)) +
geom_histogram(bins = 500) +
geom_density(outline.type = "upper", colour = "red", bw = "SJ") +
facet_wrap(~variable) +
theme_bw()
```
2. The correlations themselves
```{r}
intercepts_cor <- cor(gam_intercepts.tmp[-1] %>%
select(starts_with("F1"), starts_with("F2")))
datatable(intercepts_cor) %>%
formatRound(columns = 1:20)
```
3. A chord plot that visualises the correlations. This plot will give a more simplified representation of the above plot, it connects each of the variables to all the other variables via chords. The black chords indicate a positive correlation, whereas a red chord represents a negative correlation. The size and transparency of the chord indicates the strength of the correlation, with darker wider chords being used for the strongest correlations
The code below adapts the code used in Zuguang Gu's tutorial (see [http://jokergoo.github.io/blog/html/large_matrix_circular.html](http://jokergoo.github.io/blog/html/large_matrix_circular.html))
```{r fig.height=5, fig.width=10}
mat <- cor(gam_intercepts.tmp[-1] %>%
select(starts_with("F2"), starts_with("F1")))
diag(mat) = 0
mat[lower.tri(mat)] = 0
n = nrow(mat)
rn = rownames(mat)
group_size = c(rep(1, 20))
gl = lapply(1:20, function(i) {
rownames(mat)[sum(group_size[seq_len(i-1)]) + 1:group_size[i]]
})
names(gl) = names(mat)
group_color = structure(circlize::rand_color(20), names = names(gl))
n_group = length(gl)
col_fun = colorRamp2(c(-1, 0, 1), c("red", "transparent", "black"), transparency = 0.1)
par(mfrow=c(1,3))
# < |0.2|
mat1 <- ifelse(mat < 0.2 & mat > -0.2, mat, 0)
col2 <- col_fun(mat1)
col2 <- ifelse(col2 == "#FFFFFFE6", NA, col2)
chordDiagram(mat, col = col2, grid.col = NA, grid.border = "black",
annotationTrack = "grid", link.largest.ontop = TRUE,
preAllocateTracks = list(
list(track.height = 0.02)
)
)
title("r < |0.2|", cex.main = 2.5, line = -2)
circos.trackPlotRegion(track.index = 2, panel.fun = function(x, y) {
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
sector.index = get.cell.meta.data("sector.index")
circos.text(mean(xlim), mean(ylim), sector.index, col = "black", cex = 0.6,
facing = "inside", niceFacing = TRUE)
}, bg.border = NA)
# |0.2-0.3|
mat1 <- ifelse(mat > 0.3 | mat < -0.3, 0, mat)
mat1 <- ifelse(mat1 < 0.2 & mat1 > -0.2, 0, mat1)
col2 <- col_fun(mat1)
col2 <- ifelse(col2 == "#FFFFFFE6", NA, col2)
chordDiagram(mat, col = col2, grid.col = NA, grid.border = "black",
annotationTrack = "grid", link.largest.ontop = TRUE,
preAllocateTracks = list(
list(track.height = 0.02)
)
)
title("r between |0.2 - 0.3|", cex.main = 2.5, line = -2)
circos.trackPlotRegion(track.index = 2, panel.fun = function(x, y) {
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
sector.index = get.cell.meta.data("sector.index")
circos.text(mean(xlim), mean(ylim), sector.index, col = "black", cex = 0.6,
facing = "inside", niceFacing = TRUE)
}, bg.border = NA)
# > |0.3|
mat1 <- ifelse(mat > 0.3 | mat < -0.3, mat, 0)
col2 <- col_fun(mat1)
col2 <- ifelse(col2 == "#FFFFFFE6", NA, col2)
chordDiagram(mat, col = col2, grid.col = NA, grid.border = "black",
annotationTrack = "grid", link.largest.ontop = TRUE,
preAllocateTracks = list(
list(track.height = 0.02)
)
)
title("r between |0.3 - 0.6|", cex.main = 2.5, line = -2)
circos.trackPlotRegion(track.index = 2, panel.fun = function(x, y) {
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
sector.index = get.cell.meta.data("sector.index")
circos.text(mean(xlim), mean(ylim), sector.index, col = "black", cex = 0.6,
facing = "inside", niceFacing = TRUE)
}, bg.border = NA)
```
4. Heat map of the correlations
```{r warning=FALSE, fig.width=10, fig.height=10}
cors <- function(df) {
# turn all three matrices (r, n, and P into a data frame)
M <- Hmisc::rcorr(as.matrix(df))
# return the three data frames in a list return(Mdf)
Mdf <- map(M, ~data.frame(.x))
}
formatted_cors <- function(df){
cors(df) %>%
map(~rownames_to_column(.x, var="measure1")) %>%
map(~pivot_longer(.x, -measure1, "measure2")) %>%
bind_rows(.id = "id") %>%
pivot_wider(names_from = id, values_from = value) %>%
mutate(sig_p = ifelse(P < .05, T, F), p_if_sig = ifelse(P <.05, P, NA), r_if_sig = ifelse(P <.05, r, NA))
}
formatted_cors(gam_intercepts.tmp[-1]) %>%
ggplot(aes(x = measure1, y = measure2, fill = r, label=round(r_if_sig,2))) +
geom_tile() +
geom_text(aes(size = abs(r_if_sig)), show.legend = FALSE) +
labs(x = NULL, y = NULL, fill = "Pearson's Correlation") +
# map a red, white and blue color scale to correspond to -1:1 sequential gradient
scale_fill_gradient2(mid="#FBFEF9",low="#0C6291",high="#A63446", limits=c(-1,1)) +
theme_classic() +
# remove excess space on x and y axes
scale_x_discrete(expand=c(0,0)) +
scale_y_discrete(expand=c(0,0)) +
# change global font to roboto
theme(axis.text = element_text(size = 20, face = "bold"),
axis.text.x = element_text(angle = 90, hjust = 1),
legend.position = "top",
legend.key.width = unit(2, "cm"),
legend.title = element_text(size = 20),
legend.text = element_text(size = 20)) +
guides(fill = guide_colourbar(title.position = "top"))
```
5. Table of correlations with significance
```{r}
formatted_cors(gam_intercepts.tmp[-1]) %>%
filter(r != 1) %>%
mutate(absolute_r = abs(r)) %>%
arrange(-absolute_r) %>%
group_by(r) %>%
mutate(id = row_number()) %>%
ungroup() %>%
filter(id == 1) %>%
datatable() %>%
formatRound(c("r", "r_if_sig", "P", "p_if_sig", "absolute_r"), 3)
```
6. Permutation of correlations
This is the plot we include in the manuscript.
We show the distribution of correlation co-efficients across the intercepts (plotted in red), highlighting that there are a range of positive/negative correlations, some stronger than others.
We permute the correlations 100 times (which is a process of shuffling the values around to remove any underlying structure). This distribution is plotted in blue and shows that the random correlations are generally between |1.5|. Thus, the correlations in the ONZE dataset are likely to represent actual co-variation between the variables.
```{r fig.width=7, fig.height=7}
correlations_permuted <- gam_intercepts.tmp[-1] %>%
formatted_cors(.) %>%
mutate(intercepts = "ONZE")
for (i in 1:100) {
permuted <- formatted_cors(apply(gam_intercepts.tmp[-1], 2L, sample)) %>% mutate(intercepts = i)
correlations_permuted <<- rbind(correlations_permuted, permuted)
}
correlations_permuted <- correlations_permuted %>%
mutate(Data = ifelse(intercepts == "ONZE", "ONZE", "Permuted")) %>%
filter(r < 1)
correlations_permuted_plot <- ggplot(correlations_permuted, aes(x = r, y = ..density.., colour = Data, group = intercepts)) +
# geom_histogram(alpha = 0.1, bins = 481) +
geom_line(aes(x = r, y = P),size = 0) +
geom_density(aes(colour = Data), adjust = 0.2, size = 0.01, alpha = 1, show.legend = FALSE) +
geom_density(data = correlations_permuted %>% filter(intercepts == "ONZE"), adjust = 0.2, colour = "#F8766D", size = 1, show.legend = FALSE) +
scale_x_continuous(limits = c(-0.6, 0.6)) +
xlab("Pearson's correlation co-efficient (r)") +
# facet_grid(~intercepts) +
theme_bw() +
theme(legend.position = "top",
legend.title = element_blank(),
axis.title = element_text(size = 14, face = "bold"),
legend.text = element_text(size = 14, face = "bold")) +
guides(colour = guide_legend(override.aes = list(size=1)))
positive_correlations <- ggplot(correlations_permuted, aes(x = r, y = ..density.., colour = Data, group = intercepts)) +
geom_density(size = 0) +
annotate("rect", xmin = -1, xmax = 0.57, ymin = 2, ymax = 10, fill = "cornsilk", colour = "black") +
annotate("text", label = "Top 5 positive correlations:", fontface = 2, x = -0.95, y = 9.5, hjust = 0, vjust = 1, size = 4) +
annotate("text", label = "F1 THOUGHT ~ F2 THOUGHT (r = .49)\nF2 START ~ F2 STRUT (r = .48)\nF1 FLEECE ~ F1 START (r = .38)\nF1 GOOSE ~ F1 START (r = 0.37)\nF1 LOT ~ F1 THOUGHT (r = 0.34)", x = -0.95, y = 7.5, hjust = 0, vjust = 1, size = 4) +
theme_nothing()
negative_correlations <- ggplot(correlations_permuted, aes(x = r, y = ..density.., colour = Data, group = intercepts)) +
geom_density(size = 0) +
annotate("rect", xmin = -1, xmax = 0.57, ymin = 2, ymax = 10, fill = "cornsilk", colour = "black") +
annotate("text", label = "Top 5 negative correlations:", fontface = 2, x = -0.95, y = 9.5, hjust = 0, vjust = 1, size = 4) +
annotate("text", label = "F2 STRUT ~ F2 THOUGHT (r = -.58)\nF2 FLEECE ~ F2 NURSE (r = -.58)\nF2 START ~ F2 THOUGHT (r = -.54)\nF2 LOT ~ F2 THOUGHT (r = -.51)\nF1 LOT ~ F1 START (r = -.49)", x = -0.95, y = 7.5, hjust = 0, vjust = 1, size = 4) +
theme_nothing()
correlations_permuted_plot1 <- plot_grid(correlations_permuted_plot, plot_grid(negative_correlations, positive_correlations, nrow = 1, ncol = 2), rel_heights = c(0.8, 0.4), nrow = 2, ncol = 1)
correlations_permuted_plot1
ggsave(plot = correlations_permuted_plot1, filename = "Figures/correlations_permuted_plot.png", width = 7, height = 7, dpi = 400)
```
# Principal Components Analysis (PCA)
In the following section we will run a PCA on the `gam_intercepts.tmp` data frame, i.e. the by-speaker intercepts from each of the 20 GAMMs.
PCA offers a neat analysis solution to assessing whether there is underlying structure in the dataset, by highlighting which variables co-vary together - these are called principal components (PCs). Moreover, it also allows us to explore the data at the by-speaker level, providing us with insights into _who_ is on the margins of these PCs.
## Running the PCA
```{r}
#run the PCA on the intercepts data frame, note the intercepts are in columns 2:21 as column 1 is the speaker name
intercepts.pca <- princomp(gam_intercepts.tmp[, 2:ncol(gam_intercepts.tmp)],cor=TRUE)
#print a summary of the PCA, this will give the variance explained by each PC
summary(intercepts.pca)
#view eigen values, this will visualise the variance explained by each PC
fviz_eig(intercepts.pca, addlabels = TRUE)
#create objects containing the loadings for each of the 3 main PCs
PC1_loadings <- intercepts.pca$loadings[,1]
PC2_loadings <- intercepts.pca$loadings[,2]
PC3_loadings <- intercepts.pca$loadings[,3]
```
We can also permute the data again and run the PCA to compare how the ONZE intercepts compare to permuted intercepts. We can see a clear difference between the two data sets. The 4th PC from the ONZE intercepts does appear to explain more variance than the permuted intercepts, but we chose to focus on the first 3 PCs as each explains > 10% of the variance in the analysis (dashed horizontal line), which is commonly taken as a threshold for meaningfully interpretable PCs.
```{r}
PCA_variance_permuted <- get_eigenvalue(intercepts.pca)[1:10, 2] %>%
data.frame() %>%
rename(Variance = 1) %>%
mutate(PC = paste0(1:10),
Permutation = "ONZE",
Data = "ONZE") %>%
select(PC, Variance, Permutation, Data)