-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatisticalAnalyses.Rmd
678 lines (550 loc) · 23.9 KB
/
statisticalAnalyses.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
---
title: "Dundun Modeling"
output: html_notebook
author: Lauren K. Fink, with input from Pauline Larrouy-Maestri
contact: [email protected]
---
This notebook contains code to model data from the dundun project and generate figures.
It produces all perception-related figures from the paper (i.e., heatmap, confidence histograms, familiarity boxplot, logistic regression model), as well as the correlations among acoustic features (supplemental information). Please note that Tina Roeske analyzed all acoustic features (Figs. 1, 2, 3) in MATLAB.
## Load required packages
```{r message=FALSE}
library(lme4)
library(lmerTest)
library(car)
library(sjPlot)
library(r2glmm)
library(sjmisc)
library(sjlabelled)
library(effsize)
library(ggplot2)
library(nortest)
library(dplyr)
library(tidyverse)
library(readxl)
library(nortest)
library(PerformanceAnalytics)
library(MuMIn)
library(caret)
library(magick)
library(PEIP)
library(gplots)
library(heatmap.plus)
library(gridExtra)
```
# Load required data
NOTE: USER TODO: set files paths appropriately on your machine
Load participant and stimulus data
```{r}
# STIMULUS DATA
# mean values for each stimulus
smeans = read.csv("~/Documents/Projects/dundun/Data/dundun_acoustFeat_means_absDiffs.csv") # all acoustic features from Tina
colnames(smeans)[1] = 'Stimulus' # fix this so it matches other tables
pc = read.csv("~/Documents/Projects/dundun/Data/pulseClarity.csv") # pulse clarity values
# combine pulse clarity info with smeans
smeans$pulseClarity = pc$pulseClarity
# PARTICIPANT DATA
# Cecilia now put all behavioral data in one table
# Let's read that in and then recreate the tables we had formerly been using
pdata = read_excel("~/Documents/Projects/dundun/Data/dundun_allTrials.xlsx") # read in all data
pall = pdata[,1:31] # speech/music rating for every trial
pconf = pdata[,c(1,32:61)] # confidence for every trial
pinfo = pdata[,c(1,62:70)] # general background info about participants
pinfo$INST = pinfo$PAST.INST + pinfo$CURRENT.INST # sum current and past instrument playing to get one measure of instrument playing
pmeans = pdata[,c(1,71:81)] # mean hit rates, etc. for each participant
# OUTPUT FILE PATHS
# Set output path for figures
outpath = "~/Documents/Projects/dundun/Figures/"
op = 0 #flag whether to output plots to file (1) or plot them in line
```
# Analyze differences between acoustic features
```{r}
# t-tests for acoustic features
i = 2
for (col in smeans[,-1]){
print(colnames(smeans[i]))
# 1:15 are music, 16:30 are speech
tres = t.test(col[1:15], col[16:30], paired=FALSE)
print(tres)
print("Mean diff")
print((tres$estimate[1]-tres$estimate[2]))
print("Eff size")
d = cohen.d(col[1:15], col[16:30], paired=FALSE, within=FALSE)
print(d)
print((tres$estimate[1]-tres$estimate[2])/sd(col))
i = i+1
print("-")
print("-")
print("-")
}
```
# Look at languages represented in the participant pool and clean
```{r}
# first do some basic cleaning
pinfo$NAT.LANG = tolower(pinfo$NAT.LANG)
langs = pinfo$NAT.LANG
print(unique(langs))
# we can see there are many instances of Yoruba.. let's make those all identical
langs[langs=="yoruba language"]<-"yoruba"
langs[langs=="egun yoruba"]<-"yoruba"
langs[langs=="german and portugese"]<-"portuguese"
langs[langs=="english and mandarin"]<-"mandarin"
# or maybe let these two be unique? ^^
print(cat("\nCleaned Languages"))
print(unique(langs))
#replace our original column
pinfo$NAT.LANG = langs
# add a column for language family, in case want to report that way
# initialize column
pinfo$NAT.LANG.FAM = langs # initialize column
pmeans$Lang_cols = langs
# define language families
nc = c("bette", "yoruba", "agbor", "igbo", "ishan", "efik", "ibibio")
ie = c("german", "albanian", "serbian", "portoguese", "assamese", "english")
st = "mandarin"
aa = "hebrew"
# create binary col for yoruba
pinfo$yoruba_binary = pinfo$FAMILIARITY
for (i in 1:length(pinfo$NAT.LANG)){
if (pinfo$NAT.LANG[i] == "yoruba"){
pinfo$yoruba_binary[i] = 1
}
else{
pinfo$yoruba_binary[i] = 0
}
}
# define colors for future plotting
# familiarity will be gold (1), gray (0)
# yoruba will be black (1), white (0)
pmeans$FAMILIARITY = pinfo$FAMILIARITY
pmeans$Fam_cols = pinfo$FAMILIARITY
pmeans$Fam_cols[pmeans$Fam_cols == 1] ='gray'
pmeans$Fam_cols[pmeans$Fam_cols == 2] ='#e69d00'
pmeans$yor_cols = pinfo$yoruba_binary
pmeans$yor_cols[pmeans$yor_cols == 1] ='black'
pmeans$yor_cols[pmeans$yor_cols == 0] ='white'
```
Check number of people familiar vs unfamiliar who speak Yoruba
```{r}
print("Number of Yoruba speakers")
sum(pinfo$yoruba_binary)
print("Number of unfamiliar Yoruba speakers:")
sum(pinfo$yoruba_binary[pinfo$FAMILIARITY==1])
print("Number of familiar Yoruba speakers:")
sum(pinfo$yoruba_binary[pinfo$FAMILIARITY==2])
print("Number of familiar participants:")
print(sum(pinfo$FAMILIARITY-1))
print("Percent familiar who speak Yoruba")
print(28/51 *100)
```
# calculate other signal processing / binary classification metrics we might want to use
```{r}
# bias
pmeans$bias = -(pmeans$Hit_rate_H + pmeans$FA_rate_F)/2
# accuracy
pmeans$accuracy = 100 * ((pmeans$Hit_rate_H + pmeans$`Correct_Rejection (Speech)`)/(pmeans$Hit_rate_H + pmeans$`Correct_Rejection (Speech)` + pmeans$False_Alarm + pmeans$Miss))
# FNR
pmeans$FNR_akaMiss = 100 * (pmeans$Miss / (pmeans$Miss + pmeans$Hits_Music))
# FPR
pmeans$FPR_akaFA = 100 * (pmeans$False_Alarm / (pmeans$False_Alarm + pmeans$`Correct_Rejection (Speech)`))
# d prime (d′ = Z(hit rate) − Z(false alarm rate))
# d' music (already in table)
# d' speech (in this case it would be CR rate - miss rate)
pmeans$d_speech = pmeans$CR_rate - pmeans$Miss
# NOTE: d′ assumes that the standard deviations for signal and noise are equal, in our case they likely are not. Let's check
print(sd(pmeans$Hits_Music))
print(sd(pmeans$`Correct_Rejection (Speech)`))
# t test confirms that they are not..
print(t.test(pmeans$Hits_Music, pmeans$`Correct_Rejection (Speech)`))
# mcc
# https://en.wikipedia.org/wiki/Matthews_correlation_coefficient
# https://bmcgenomics.biomedcentral.com/articles/10.1186/s12864-019-6413-7#citeas
# first the numerator
pmeans$numerator = ( (pmeans$Hits_Music * pmeans$`Correct_Rejection (Speech)`) - (pmeans$Miss * pmeans$False_Alarm) )
# now denominator
pmeans$denominator = sqrt((pmeans$Hits_Music + pmeans$False_Alarm) * (pmeans$Hits_Music+pmeans$Miss) * (pmeans$`Correct_Rejection (Speech)` + pmeans$False_Alarm) * (pmeans$`Correct_Rejection (Speech)`+pmeans$Miss))
pmeans
# NOTE will have zero in denominator for e.g. people who FA everything. Set this to 1 (as recommended)
pmeans$denominator[pmeans$denominator==0] = 1
# now calculate mcc
pmeans$mcc = pmeans$numerator / pmeans$denominator
```
# Create long form table of participant responses for future modeling
```{r}
# convert into long form
prating_long = pall %>%
pivot_longer(!Participant, names_to = "Stimulus", values_to = "Rating")
pconf_long = pconf %>%
pivot_longer(!Participant, names_to = "Stimulus", values_to = "Confidence")
# combine ratings and confidence into one table
long_all = prating_long
long_all$Confidence = pconf_long$Confidence
# add column with number for class of stim
musInds = grep("M", long_all$Stimulus)
speechInds = grep("S", long_all$Stimulus)
long_all$Class = NA
long_all$Class[musInds] = 2
long_all$Class[speechInds] = 1
# add column for error
long_all$Error = NA
long_all$Error = long_all$Class - long_all$Rating
# normalize confidence by participant?
long_all$Conf_norm = NA
long_all = long_all %>%
group_by(Participant) %>%
mutate(Conf_norm = (Confidence - mean(Confidence))/std(Confidence))
# do left inner joins on other participant and stimulus level features we might want
pinfo$Participant = rownames(pinfo)
long_all = merge(x = long_all, y = pinfo, by = "Participant", all.x = TRUE)
# merge stimulus info into long table
long_all = merge(x = long_all, y = smeans, by = "Stimulus", all.x = TRUE)
```
There are 15 unique languages represented in the dataset ("undecided" does not count)
## Analyze participant responses
```{r}
########################################################################################
# Print out matrix of different error types
########################################################################################
# look at total errors in subs vs stims
# need to just get to 0 (no error) or 1 (error)
error_pall = subset(pall, select = -c(Participant) ) # remove participant column
error_pall[,1:15] = error_pall[,1:15] - 2 # subtract 2 from music (this results in 0 if no error)
error_pall[,16:30] = error_pall[,16:30] - 1 # subtract 1 from speech (this results in 0 if no error)
error_pall = abs(error_pall)
# get some summary statistics
sub_errors = rowSums(error_pall)
music_errors = colMeans(error_pall[1:15])
speech_errors = colMeans(error_pall[16:30])
pmeans$sub_errors = sub_errors
pall$sub_errors = sub_errors
stim_errors = colSums(error_pall[1:30])
pmeans = pmeans[order(pmeans$sub_errors),]
# print out number of absolute errors
print("Range of confusions for each participant")
print(range(sub_errors))
print("Range of confusions for each stimulus")
print(range(stim_errors))
print("Number of subs with no errors:")
print(sum(sub_errors == 0))
# print out total errors by type
# can get this from table of means already provided by Pauline
print("Speech / Speech")
print(sum(pmeans$`Correct_Rejection (Speech)`))
print("Speech / Music")
print(sum(pmeans$False_Alarm))
print("Music / Speech")
print(sum(pmeans$Miss))
print("Music / Music")
print(sum(pmeans$Hits_Music))
print("Average acccuracy across participants")
print(mean(pmeans$accuracy))
print(sd(pmeans$accuracy))
print("Average FNR across participants")
print(mean(pmeans$FNR_akaMiss))
print(sd(pmeans$FNR_akaMiss))
print("Average FPR across participants")
print(mean(pmeans$FPR_akaFA))
print(sd(pmeans$FPR_akaFA))
# ahh but these are susceptible to extremes, so maybe better to go with the normalized rates Pauline already computed?
# Seems they are identical..
print("Average miss rate (norm) across participants")
print(mean(pmeans$Miss_rate))
print(sd(pmeans$Miss_rate))
print("Average FA rate (norm) across participants")
print(mean(pmeans$FA_rate_F))
print(sd(pmeans$FA_rate_F))
print("Average mcc across participants")
print(mean(pmeans$mcc))
print(sd(pmeans$mcc))
# run t-test on d' for familiar vs. unfamilar participants
tres = t.test(pmeans$mcc[pmeans$FAMILIARITY==2], pmeans$mcc[pmeans$FAMILIARITY==1], paired=FALSE)
d = cohen.d(pmeans$mcc[pmeans$FAMILIARITY==2], pmeans$mcc[pmeans$FAMILIARITY==1], paired=FALSE, within=FALSE)
print(tres)
print(d)
print("Difference between means")
print(tres$estimate[1] - tres$estimate[2])
```
For reviewer, check subgroup who was familiar but did not speak yoruba
```{r}
# run t-test on d' for familiar non-yoruba vs. unfamilar participants
tres = t.test(pmeans$mcc[pmeans$FAMILIARITY==2 & pmeans$yor_cols=="white"], paired=FALSE)
d = cohen.d(pmeans$mcc[pmeans$FAMILIARITY==2], pmeans$mcc[pmeans$FAMILIARITY==1], paired=FALSE, within=FALSE)
print(tres)
print(d)
print("Difference between means")
print(tres$estimate[1] - tres$estimate[2])
```
```{r}
########################################################################################
# analyze confidence
# conf_means_stims = colMeans(pconf[,-1])
# print("Mean confidence:")
# quick function to make plot we want
plot_conf_fam_hist = function(unfam, fam){
# should feed unfam$confidence and fam$confidence
uf = hist(unfam, freq=FALSE, breaks = seq(from=.5, to=4.5, by=1), col=rgb(.192, .192, .192, .5), main="", xlab="Confidence", ylim=c(0,1))
f = hist(fam, freq=FALSE, breaks = seq(from=.5, to=4.5, by=1), col=rgb(.9,.62, 0, .5), add=TRUE, main="", xlab="Confidence", ylim=c(0,1))
}
########################################################################################
# look at avg conf for each error type
########################################################################################
# music --> speech (Miss)
if (op) {tiff(paste(outpath, "dundun_conf_MS.tiff", sep=""), units="in", width=3, height=3, res=300)}
hist(long_all$Confidence[long_all$Error == 1], breaks = seq(from=.5, to=4.5, by=1))
#axis(side=1, at=seq(0,120,40), labels=c(0,40,80, 120))
print("music / speech")
print(mean(long_all$Confidence[long_all$Error == 1]))
# add familiarity to plot
d1 = long_all[(long_all$Error == 1) & (long_all$FAMILIARITY==1),]
d2 = long_all[(long_all$Error == 1) & (long_all$FAMILIARITY==2),]
if (op){tiff(paste(outpath, "dundun_confFAM_MS.tiff", sep=""), units="in", width=4, height=3, res=300)}
plot_conf_fam_hist(d1$Confidence, d2$Confidence)
print("Unfamiliar")
print(mean(d1$Confidence))
print("Familiar")
print(mean(d2$Confidence))
########################################################################################
# speech --> music (FA)
if (op){tiff("dundun_conf_SM.tiff", units="in", width=3, height=3, res=300)}
hist(long_all$Confidence[long_all$Error == -1], breaks = seq(from=.5, to=4.5, by=1))
print("speech / music")
print(mean(long_all$Confidence[long_all$Error == -1]))
d1 = long_all[(long_all$Error == -1) & (long_all$FAMILIARITY==1),]
d12 = long_all[(long_all$Error == -1) & (long_all$FAMILIARITY==2),]
if (op){tiff(paste(outpath, "dundun_confFAM_SM.tiff", sep=""), units="in", width=4, height=3, res=300)}
plot_conf_fam_hist(d1$Confidence, d2$Confidence)
print("Unfamiliar")
print(mean(d1$Confidence))
print("Familiar")
print(mean(d2$Confidence))
########################################################################################
# hits music (Hit)
if (op){tiff("dundun_conf_MM.tiff", units="in", width=3, height=3, res=300)}
hist(long_all$Confidence[(long_all$Error == 0) & (long_all$Class == 2)], breaks = seq(from=.5, to=4.5, by=1))
print("music / music")
print(mean(long_all$Confidence[(long_all$Error == 0) & (long_all$Class == 2)]))
d1 = long_all[(long_all$Error == 0) & (long_all$Class == 2) & long_all$FAMILIARITY == 1,]
d2 = long_all[(long_all$Error == 0) & (long_all$Class == 2) & long_all$FAMILIARITY == 2,]
if (op){tiff(paste(outpath, "dundun_confFAM_MM.tiff", sep=""), units="in", width=4, height=3, res=300)}
plot_conf_fam_hist(d1$Confidence, d2$Confidence)
print("Unfamiliar")
print(mean(d1$Confidence))
print("Familiar")
print(mean(d2$Confidence))
########################################################################################
# hits speech (correct rejections)
if (op){tiff("dundun_conf_SS.tiff", units="in", width=3, height=3, res=300)}
hist(long_all$Confidence[(long_all$Error == 0) & (long_all$Class == 1)], breaks = seq(from=.5, to=4.5, by=1))
print("speech / speech")
print(mean(long_all$Confidence[(long_all$Error == 0) & (long_all$Class == 1)]))
if (op){tiff(paste(outpath, "dundun_confFAM_SS.tiff", sep=""), units="in", width=4, height=3, res=300)}
d1 = long_all[(long_all$Error == 0) & (long_all$Class == 1) & long_all$FAMILIARITY == 1,]
d2 = long_all[(long_all$Error == 0) & (long_all$Class == 1) & long_all$FAMILIARITY == 2,]
plot_conf_fam_hist(d1$Confidence, d2$Confidence)
print("Unfamiliar")
print(mean(d1$Confidence))
print("Familiar")
print(mean(d2$Confidence))
```
```{r}
########################################################################################
# Create heatmap
########################################################################################
# sort matrices by numbers of errors
pall = pall[order(pall$sub_errors),]
for_hm = pall[,-c(1,ncol(pall))]
mean_stim_errors = colMeans(error_pall)
for_hm = for_hm[,c(order(music_errors), order(speech_errors)+15)]
if (op){tiff("dundunPerception_allSubs_rev1_yor.tiff", units="in", width=15, height=27, res=300)}
heatmap.2(data.matrix(for_hm),
scale="none",
xlab="", ylab="",
col=c("red", "blue"),
dendrogram="none", #"col",
Rowv=FALSE,
trace="none",
#RowSideColors = pmeans$Fam_cols,
RowSideColors = pmeans$yor_cols,
key=FALSE,
density.info = "none",
cexCol = 2,
labRow = FALSE,
Colv=FALSE,
)
```
Plot heatmap with yoruba and familiarity
```{r}
#if (op){png("dundunPerception_allSubs_rev1_yorFam.png", units="in", width=15, height=27, res=300)}
heatmap.plus(data.matrix(for_hm),
scale="none",
xlab="", ylab="",
col=c("red", "blue"),
Rowv=NA,
RowSideColors = cbind(pmeans$yor_cols, pmeans$Fam_cols),
cexCol = 2,
labRow = FALSE,
Colv=NA,
keep.dendro=FALSE
)
```
```{r}
########################################################################################
# Create box plot (with underlying points) for mcc
########################################################################################
# recode familiarity to display how we want on plot
pmeans$Familiarity = pmeans$FAMILIARITY
pmeans$Familiarity[pmeans$Familiarity==1]<-"Unfamiliar"
pmeans$Familiarity[pmeans$Familiarity==2]<-"Familiar"
pmeans$Familiarity = as.factor(pmeans$Familiarity)
if (op){tiff("dundun_mcc2_rev1.tiff", units="in", width=5, height=7, res=300)}
pmeans %>%
ggplot( aes(x=Familiarity, y=mcc, group=Familiarity, fill=Familiarity, color = Familiarity)) +
# geom_boxplot(outlier.shape = NA) + # don't plot outlier because will be ovelaid by jitter point (and look like two points instead of the one that it is)
geom_violin(draw_quantiles = c(.25,.5,.75)) +
scale_color_manual(values=c("black", "black")) +
scale_fill_manual(values=c("#e69d00", "grey")) +
geom_jitter(size=2, alpha=0.3, width=.2) +
theme_classic() +
theme(
legend.position="none",
text = element_text(size=20, color="black"),
panel.grid.minor.y = element_blank(),
) +
ylim(-1.1, 1.1) +
xlab("") +
ylab("MCC")
```
# Build predictive model
We ultimately want to predict participants' perception from the acoustic and participant features. Therefore we first need to get a sense of the relationships among predictors.
#### Check for correlations among acoustic features
```{r}
# remove ratio diff and other columns we don't need
acoust_feats = smeans[ , -which(names(smeans) %in% c("Filename","Stimulus", "Category", "ratioDiff"))] # drop label columns and ones not using
# rearrange ams to be first (how we want in paper)
acoust_feats <- acoust_feats %>%
select(AMS_peak, everything())
# rename cols for how we want to display in paper
acoust_feats = acoust_feats %>% rename(intensity = amp, intensity_chg = ampDiff, pitch_chg = pitchDiff, entropy = ent, entropy_chg = entDiff, IOI = o2o, pulse_clarity = pulseClarity)
if (op){png("dundun_acousticCorrs.png", units="in", width=11, height=8, res=300)}
chart.Correlation(acoust_feats, histogram=TRUE, pch=25, text.panel=labs)
```
Amp diff has a very high correlation with o2o and amp. Might need to get rid. Will check VIFs.
```{r}
# quick plot of distribution of pulse clarity
tp = smeans
tp$Category[1:15] = "Music"
tp$Category[16:30] = "Speech"
if (op){tiff("dundun_pulseClarity.tiff", units="in", width=5, height=7, res=300)}
j = ggplot(data=tp,aes(x=Category, y=pulseClarity, group=Category,fill=Category, colour=Category))+
geom_violin(draw_quantiles = .5) +
#geom_boxplot(outlier.shape = NA) +
#geom_point() +
geom_jitter(width=.1) +
theme_classic() +
theme(
legend.position="none",
text = element_text(size=20, color="black"),
panel.grid.minor.y = element_blank(),
) +
xlab("") +
ylim(0,.5) +
ylab("Pulse Clarity")
j + scale_fill_manual(values=c("#0000FF", "#FF0000")) + scale_color_manual(values=c("#000000", "#000000"))
```
```{r}
# re-code some variables for model
long_all$Rating = long_all$Rating -1 # subtract 1 to get binary 0 (speech) 1 (music)
long_all$FAMILIARITY = long_all$FAMILIARITY-1 # again subtract 1 so binary
long_all$INST = long_all$INST -2 # subtract 2 so logically have 0,1,2
long_all$Confidence = long_all$Confidence-1 # again to have scale start at 0 no conf
# Center these person level vars? No because it would confuse interpretation
# remove the 4 participants who always answered music? TODO CHECK
# does not make a difference
# Participants 7, 9, 10, 51
# test = long_all
# test = subset(long_all, Participant != c(7, 9, 10,51))
# long_all = test
# Scale acoustic features
# NOTE: Tina has already scaled acoustic features between 2nd and 98th percentiles in Matlab. However, we still get scale warnings if we include them the way they are.. so..
long_all$amp = scale(long_all$amp, center=TRUE, scale=TRUE)
long_all$ampDiff = scale(long_all$ampDiff, center=TRUE, scale=TRUE)
long_all$ent = scale(long_all$ent, center=TRUE, scale=TRUE)
long_all$entDiff = scale(long_all$entDiff, center=TRUE, scale=TRUE)
long_all$pitch = scale(long_all$pitch, center=TRUE, scale=TRUE)
long_all$pitchDiff = scale(long_all$pitchDiff, center=TRUE, scale=TRUE)
long_all$ratio = scale(long_all$ratio, center=TRUE, scale=TRUE)
long_all$ratioDiff = scale(long_all$ratioDiff, center=TRUE, scale=TRUE)
long_all$o2o = scale(long_all$o2o, center=TRUE, scale=TRUE)
long_all$AMS_peak = scale(long_all$AMS_peak, center=TRUE, scale=TRUE)
long_all$pulseClarity = scale(long_all$pulseClarity, center=TRUE, scale=TRUE)
# full model with familiarity interactions
# lr <- glmer(Rating ~ FAMILIARITY + Confidence + Confidence*FAMILIARITY + AMS_peak + AMS_peak*FAMILIARITY + amp + amp*FAMILIARITY + pitch + pitch*FAMILIARITY + ent + ent*FAMILIARITY + entDiff + ampDiff + ampDiff*FAMILIARITY + pitchDiff + pitchDiff*FAMILIARITY + entDiff*FAMILIARITY + o2o + o2o*FAMILIARITY + ratio + ratio*FAMILIARITY +(1|Stimulus) + (1|Participant),
# data=long_all,
# family=binomial(link="logit"),
# na.action=na.exclude,
# control=glmerControl(optimizer="bobyqa",
# optCtrl=list(maxfun=2e5)))
# summary(lr)
# print(car::vif(lr))
# final with terms with high VIF deleted
lr <- glmer(Rating ~ FAMILIARITY + Confidence + Confidence*FAMILIARITY + AMS_peak + AMS_peak*FAMILIARITY + amp + amp*FAMILIARITY + pitch + pitch*FAMILIARITY + ent + ent*FAMILIARITY + + pitchDiff + pitchDiff*FAMILIARITY + entDiff + entDiff*FAMILIARITY + entDiff*FAMILIARITY + ratio + ratio*FAMILIARITY + pulseClarity + pulseClarity*FAMILIARITY +(1|Stimulus) + (1|Participant),
data=long_all,
family=binomial(link="logit"),
na.action=na.exclude,
control=glmerControl(optimizer="bobyqa",
optCtrl=list(maxfun=2e5)))
summary(lr)
print(car::vif(lr))
```
None of our VIFs are over 5 so we should be ok to keep all predictors.
Let's calculate some classification metrics of interest for the model
```{r}
long_all$p <- as.numeric(predict(lr, type="response")>0.5)
print("Prediction Accuracy:")
print(mean(long_all$p==long_all$Rating))
cm = table(long_all$p,long_all$Rating)
print(cm)
tp = 1656
tn = 1081
fp = 247
fn = 226
# mcc = ( (cm[4]*cm[1]) - (cm[3]*cm[2]) ) / sqrt( (cm[4]+cm[3])*(cm[4]+cm[2])*(cm[1]+cm[3])*(cm[1]+cm[2]))
# NOTE: hard-coding this because not sure how to deal with the L formatting from the cm table. Needed quick answer. TODO fix eventually +!
mcc = ((tp*tn) - (fp*fn)) / sqrt( (tp+fp)*(tp+fn)*(tn+fp)*(tn+fn) )
print("MCC:")
print(mcc)
```
Now let's make some plots
```{r}
# plot residuals
plot(lr)
# plot fixed effect estimates + CIs
plot_model(lr, show.values = TRUE, type = "est", value.offset = .4)
# plot marginal effects of specifc predictors
plot_model(lr, type = "pred", terms = "amp")
# plot marginal effects of specifc predictors
plot_model(lr, type = "int")
# Diagnostics
plot_model(lr, show.values = TRUE, type = "diag")
# plot random effects
plot_model(lr, type = "re") #show.values = TRUE)
```
```{r}
# save plot we want to file
# fixed effect estimates + CIs
p = plot_model(lr, show.values = TRUE, type = "est", value.offset = .4, axis.lim= c(.2,5))
if (op){tiff("dundun_perceptionLogisticModel_rev1.tiff", units="in", width=11, height=8, res=300)}
p
# p + theme_blank()
# p + theme_sjplot2()
# p + theme_minimal()
```
```{r}
# check if overparameterized
print(rePCA(lr)) #not overparameterized
# Do F test for model
print(Anova(lr))
# Output table with fixed and random effect results
sjPlot::tab_model(lr,
show.re.var= TRUE)
#print(r2beta(lr, method = "nsj")) # variance explained by each fixed effect
```