-
Notifications
You must be signed in to change notification settings - Fork 0
/
md1_analyses.Rmd
2099 lines (1779 loc) · 110 KB
/
md1_analyses.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: "ManyDogs 1 Analyses"
author: "ManyDogs Project et al."
date: "`r Sys.Date()`"
mainfont: Times
bibliography: r-references.bib
output:
bookdown::pdf_document2:
number_sections: false
toc: false
header-includes:
- \usepackage{pdflscape}
---
```{r setup-demo, include = FALSE}
# Set up knitr options
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
# Load packages
library(tidyverse)
library(here)
library(lme4)
library(car)
library(psych)
library(BayesFactor)
library(ggdist)
library(gghalves)
library(ggpubr)
library(patchwork)
library(knitr)
library(kableExtra)
library(flextable)
library(papaja)
# Needed for Bayesian analyses
# library(brms)
# library(bayestestR)
# library(performance)
# library(gtools)
# library(data.table)
# library(bayesplot)
# library(tidybayes)
# library(glue)
# library(coda)
# library(MCMCglmm)
# library(broom.mixed)
# Install additional packages
# If you haven't installed tinytex
# tinytex::install_tinytex()
# Probably best to install rstan directly from Stan
# Run the next line if you already have rstan installed
# remove.packages(c("StanHeaders", "rstan"))
# install.packages("rstan", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
# If you haven't installed cmdstanr
# install.packages("cmdstanr", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
# cmdstanr::install_cmdstan()
# Needed for Arial font in Linux; uncomment if needed
extrafont::loadfonts(quiet = TRUE)
# Create citations for R and R packages
r_refs(file = "r-references.bib")
my_citations <- cite_r(file = "r-references.bib", pkgs = c("BayesFactor", "bayesplot", "bayestestR", "brms", "broom.mixed", "car", "coda", "data.table", "flextable", "ggdist", "gghalves", "ggpubr", "glue", "gtools", "here", "kableExtra", "knitr", "lme4", "MCMCglmm", "papaja", "patchwork", "performance", "psych", "rmarkdown", "rstan", "tidybayes", "tidyverse"), omit = FALSE)
# Prepare computing environment for parallel processing
# These analyses take a lot of time and processing to compute 95% CI bootstraps and Bayes factors. Several code chunks use parallel processing, and this section sets up the cores and threads for the parallelization.
# CI bootstraps
n_cores_ci <- 4 # number of physical CPU cores on your machine you want to use for CI bootstraps
n_threads_ci <- 4 # number of threads per core you want to use for CI bootstraps
n_cpu_ci <- n_cores_ci * n_threads_ci # total threads you want to use for CI bootstraps (should be probably no more than 75% of total threads available)
# Bayesian analyses
n_cores_bf <- 4 # number of physical CPU cores on your machine you want to use for Bayes factors
n_threads_bf <- 3 # number of threads per core you want to use for Bayes factors
n_cpu_bf <- n_cores_bf * n_threads_bf # total threads you want to use for Bayes factors (if you have 4 cores and at least 3 threads per core, I would use this---more threads doesn't speed up processing)
set.seed(1)
```
```{r functions}
# Define functions
# Calculate demographics for each site
calculate_site_demographics <- function(data, measure, overall = TRUE) {
# measure <- sym(measure)
measure_vec <- pull(data, {{ measure }})
measure_str <- sub("\\.data\\[\\[\"", "", enexpr(measure))[3]
if (is.character(measure_vec)) {
if(overall) {
data %>%
count({{ measure }}) |>
pivot_wider(names_from = {{ measure }}, values_from = n) %>%
rename_with(~ paste0(measure_str, "_", tolower(.x)))
} else {
data %>%
count(site, {{ measure }}) |>
complete(site, {{ measure }}) |>
mutate(n = replace_na(n, 0)) |>
pivot_wider(id_cols = site, names_from = {{ measure }}, values_from = n) %>%
rename_with(~ paste0(measure_str, "_", tolower(.x)))
}
} else if (is.numeric(measure_vec)) {
data %>%
{if (!overall) group_by(., site) else . } %>%
summarise(n = n(),
mean = mean({{ measure }}, na.rm = TRUE),
sd = sd({{ measure }}, na.rm = TRUE),
min = min({{ measure }}, na.rm = TRUE),
max = max({{ measure }}, na.rm = TRUE)) %>%
rename_with(.cols = mean:max, ~ paste0(measure_str, "_", .x))
} else {
stop("Wrong data type for measure.")
}
}
# Calculate inter-rater reliablity for each site
calculate_site_reliability <- function(sitename) {
site_data <- included_data |>
filter(site == sitename) |>
select(choice, recoded_choice) |>
drop_na()
cohen.kappa(cbind(site_data$choice, site_data$recoded_choice))
}
# Calculate one-sample t-tests
calculate_ttests <- function(sitename = NULL) {
if (!is.null(sitename)) {
df <- filter(agg_data, site == sitename)
} else {
df <- agg_data
}
df_ost <- filter(df, condition == "ostensive")
df_nonost <- filter(df, condition == "nonostensive")
df_odor <- filter(df, condition == "odor")
# Frequentist
tt_ost <- t.test(df_ost$mean_correct, mu = 0.5, alternative = "two.sided")
tt_nonost <- t.test(df_nonost$mean_correct, mu = 0.5, alternative = "two.sided")
tt_odor <- t.test(df_odor$mean_correct, mu = 0.5, alternative = "two.sided")
# Bayes factors
tt_ost_bf <- ttestBF(df_ost$mean_correct, mu = 0.5, alternative = "two.sided")
tt_nonost_bf <- ttestBF(df_nonost$mean_correct, mu = 0.5, alternative = "two.sided")
tt_odor_bf <- ttestBF(df_odor$mean_correct, mu = 0.5, alternative = "two.sided")
return(list(tt_ost = tt_ost, tt_nonost = tt_nonost, tt_odor = tt_odor,
tt_ost_bf = tt_ost_bf, tt_nonost_bf = tt_nonost_bf, tt_odor_bf = tt_odor_bf))
}
# Clean up effects columns for model tables
clean_effects <- function(x) {
names(x)[1] <- "effect"
x |>
filter(!effect %in% c("sexMale", "desexedYes")) |>
mutate(effect = gsub("<none>", "(Intercept)", effect),
effect = gsub("Yes", "", effect),
effect = gsub("Male", "", effect),
effect = gsub("sexM", "Sex", effect),
effect = gsub("ostensive", "", effect),
effect = gsub("condition\\_orderost", "condition\\_order", effect),
effect = gsub("ost\\_first", "", effect),
effect = gsub("\\_z", "", effect),
effect = gsub("num", "number", effect),
effect = gsub("biasyes", "bias", effect),
effect = str_to_sentence(gsub("\\_", " ", effect))
)
}
# Calculate t-tests per site
ost_nonost_ttests <- function(sitename = NULL) {
if (!is.null(sitename)) {
x <- filter(agg_data, site == sitename)
} else {
x <- agg_data
}
x <- x |>
filter(grepl("ostensive", condition)) |>
pivot_wider(id_cols = c(site, subjectID), names_from = condition, values_from = mean_correct) |>
drop_na()
ost_ttest <- t.test(x$ostensive, x$nonostensive, paired = TRUE)
pvalue <- ost_ttest$p.value
ost_ttestbf <- ttestBF(x$ostensive, x$nonostensive, paired = TRUE)
bf <- extractBF(ost_ttestbf)$bf
return(paste0(" N = ", nrow(x), "\np = ", apa_num(pvalue, digits = 3), "\nBF = ", round(bf, 2)))
}
# Convert numerals less than 10 to words
word_nums <- c("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
make_word_nums <- function (x) ifelse(x < 10, word_nums[x + 1], x)
# Create model formulas by dropping predictors
drop_predictor <- function(x) {
if (!grepl(x, fixed_effects)) {
stop("That predictors was not found in the fixed effects.")
}
paste0(sub(paste(x, "\\+"), "", fixed_effects), " ", random_effects)
}
# Import external functions
source(here("md1_functions.R"))
```
# Methods
## Data analysis
We analyzed data from the project using `r my_citations`. Data, analysis scripts, and pre-registered methods (videos) are available at the Open Science Framework (https://osf.io/9r5xf/), as is pre-registration of our design and analysis plan (https://doi.org/10.17605/OSF.IO/GZ5PJ).
# Results
## Pilot data
```{r import-data-pilot}
# Import pilot data
pilot_data <- read_csv(here("md1_data_pilot.csv"), show_col_types = FALSE)
```
### _Demographics_
```{r demographics-pilot}
# Calculate demographic information for pilot data
demographics_pilot <- pilot_data |>
group_by(subjectID) |>
slice_head() |>
ungroup()
demographics_measures_pilot <- c("age", "sex", "desexed", "purebred")
demographics_overall_pilot <- map_dfc(demographics_measures_pilot,
~ calculate_site_demographics(demographics_pilot, .data[[.x]]),
overall = TRUE) |>
mutate(site = "Overall", .before = 1)
```
```{r breed-info-pilot}
# Find number of each breed in pilot data
breeds_pilot <- pilot_data |>
group_by(subjectID) |>
slice_head(n = 1) |>
ungroup() |>
count(breed) |>
drop_na() |>
arrange(desc(n))
n_breeds_pilot <- nrow(filter(breeds_pilot, n >= 8))
```
In the pilot experiment, we tested `r demographics_overall_pilot$n` dogs (M:F = `r demographics_overall_pilot$sex_m`:`r demographics_overall_pilot$sex_f`, mean±SD age = `r round(demographics_overall_pilot$age_mean, 1)`±`r round(demographics_overall_pilot$age_sd, 1)` years [range = `r demographics_overall_pilot$age_min`-`r demographics_overall_pilot$age_max`]). Approximately `r round(demographics_overall_pilot$desexed_yes / (demographics_overall_pilot$desexed_yes + demographics_overall_pilot$desexed_no) * 100, 1)`% of the dogs were spayed or neutered, `r round(demographics_overall_pilot$purebred_yes / (demographics_overall_pilot$purebred_yes + demographics_overall_pilot$purebred_no) * 100, 1)`% were purebred, and all lived in private homes.
```{r aggregate-data-pilot}
# Aggregate pilot data for conditions
agg_data_pilot <- pilot_data |>
group_by(subjectID, sex, breed, age, training, condition) |>
summarise(mean_correct = mean(correct, na.rm = TRUE), .groups = "drop")
n_subjects_pilot <- agg_data_pilot |>
slice_head(by = subjectID) |>
nrow()
agg_data_noodor_pilot <- agg_data_pilot |>
filter(condition != "odor") |>
mutate(cond_jitter = jitter(as.numeric(as.factor(condition)), amount = 0.1),
cond_num = case_when(condition == "nonostensive" ~ 1,
condition == "ostensive" ~ 2,
.default = NA))
agg_data_ostensive_pilot <- agg_data_noodor_pilot |>
filter(condition == "ostensive")
agg_data_nonostensive_pilot <- agg_data_noodor_pilot |>
filter(condition == "nonostensive")
agg_data_odor_pilot <- agg_data_pilot |>
mutate(condition=as.factor(condition))|>
filter(condition == "odor")
```
### _Performance Relative to Chance_
```{r t-tests-pilot}
# Calculate one-sample t-tests for each condition for pilot data
tt_ost_pilot <- t.test(agg_data_pilot$mean_correct[agg_data_pilot$condition == "ostensive"], mu = 0.5, alternative = "two.sided")
tt_non_pilot <- t.test(agg_data_pilot$mean_correct[agg_data_pilot$condition == "nonostensive"], mu = 0.5, alternative = "two.sided")
tt_odor_pilot <- t.test(agg_data_pilot$mean_correct[agg_data_pilot$condition == "odor"], mu = 0.5, alternative = "two.sided")
# Calulate Bayes factors for t-tests
tt_ost_bf_pilot <- ttestBF(agg_data_pilot$mean_correct[agg_data_pilot$condition == "ostensive"], mu = 0.5, alternative = "two.sided")
tt_non_bf_pilot <- ttestBF(agg_data_pilot$mean_correct[agg_data_pilot$condition == "nonostensive"], mu = 0.5, alternative = "two.sided")
tt_odor_bf_pilot <- ttestBF(agg_data_pilot$mean_correct[agg_data_pilot$condition == "odor"], mu = 0.5, alternative = "two.sided")
```
The dogs (N = `r n_subjects_pilot`) performed better than expected by chance in the Ostensive condition (`r apa_ttest(tt_ost_pilot, digits = 2)`, `r format_bf(tt_ost_bf_pilot)`) but not in the Non-ostensive condition (`r apa_ttest(tt_non_pilot, digits = 2)`, `r format_bf(tt_non_bf_pilot)`) or the Odor Control condition (`r apa_ttest(tt_odor_pilot, digits = 2)`, `r format_bf(tt_odor_bf_pilot)`) (Figure S6).
### _Condition Comparison_
```{r model-building-pilot}
# Build models for pilot data
# Center and scale variables for modeling
model_data_pilot <- pilot_data |>
filter(condition == "ostensive" | condition == "nonostensive") |>
mutate(
age_z = as.numeric(scale(age, scale = TRUE, center = TRUE)),
trial_num_z = as.numeric(scale(trial, scale = TRUE, center = TRUE)),
training_score_z = as.numeric(scale(training, scale = TRUE,
center = TRUE)),
condition_c = as.numeric(scale(as.numeric(as.factor(condition)),
scale = FALSE, center = TRUE)),
condition_order_c = as.numeric(scale(as.numeric(as.factor(condition_order)),
scale = FALSE, center = TRUE)),
sex_c = as.numeric(scale(as.numeric(as.factor(sex)), scale = FALSE,
center = TRUE))
)
# Define full models (with and without correlations in random effects)
fixed_effects_pilot <- "correct ~ condition + condition_order + trial_num_z + sex + age_z + training_score_z +"
random_effects_corr_pilot <- "(condition_c + trial_num_z | subjectID)"
random_effects_nocorr_pilot <- "(condition_c + trial_num_z || subjectID)"
full_model_formula_corr_pilot <- paste(fixed_effects_pilot, random_effects_corr_pilot)
full_model_formula_nocorr_pilot <- paste(fixed_effects_pilot, random_effects_nocorr_pilot)
```
```{r run-model-pilot, eval = FALSE, include = FALSE}
# Run the full models with and without correlations for pilot data
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
# Set model control parameters and random seed
contr <- glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 10000000), calc.derivs = FALSE)
set.seed(100)
# Run full models (with and without correlations)
full_model_corr_pilot <- glmer(full_model_formula_corr_pilot, family = binomial,
data = model_data_pilot, control = contr, nAGQ = 0)
full_model_nocorr_pilot <- glmer(full_model_formula_nocorr_pilot, family = binomial,
data = model_data_pilot, control = contr, nAGQ = 0)
# Compare models
summary(full_model_corr_pilot)$log
summary(full_model_nocorr_pilot)$log
# Model with no correlations has better fit (lower log-likelihood), so use that model
# Set effects and build model formula
random_effects_pilot <- random_effects_corr_pilot
full_model_formula_pilot <- full_model_formula_corr_pilot
full_model_pilot <- full_model_corr_pilot
full_model_table_pilot <- as.data.frame(summary(full_model_pilot)$coefficients) |>
rownames_to_column(var = "effect_full")
write_csv(full_model_table_pilot, here("results/md1_full_model_pilot.csv"))
## Calculate likelihood ratio test
drop1_full_model_pilot <- drop1(full_model_pilot, test = "Chisq", control = contr)
drop1_full_model_rownames_pilot <- rownames(drop1_full_model_pilot)
drop1_full_model_table_pilot <- tibble(effect_drop = drop1_full_model_rownames_pilot, drop1_full_model_pilot)
write_csv(drop1_full_model_table_pilot, here("results/md1_drop_model_pilot.csv"))
```
```{r bootstrap-cis-pilot, eval = FALSE, include = FALSE}
# Calculate bootstrapped 95% confidence intervals for model estimates for pilot data
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
set.seed(300)
full_model2_pilot <- glmer(full_model_formula_pilot, family = binomial, data = model_data_pilot,
control = glmerControl(optimizer = "bobyqa",
optCtrl = list(maxfun = 10000000),
calc.derivs = FALSE), nAGQ = 0)
full_model_ci_pilot <- boot.glmm.pred(model.res = full_model2_pilot, excl.warnings = TRUE,
nboots = 1000, para = TRUE, n.cores = n_cpu_ci,
level = 0.95)
full_model_ci_estimates_pilot <- full_model_ci_pilot$ci.estimates
full_model_ci_estimatesl_rownames_pilot <- rownames(full_model_ci_estimates_pilot)
full_model_ci_estimates_table_pilot <- tibble(effect_ci = full_model_ci_estimatesl_rownames_pilot, full_model_ci_estimates_pilot)
write_csv(full_model_ci_estimates_table_pilot, here("results/md1_ci_model_pilot.csv"))
```
```{r bayes-factors-pilot, eval = FALSE, include = FALSE}
# Run the full Bayesian models with and without correlations for pilot data
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
# Prepare computing environment for Bayesian analysis
n_chains <- 4L
total_draws <- 40000
n_warmup <- 5000
n_iter <- round((total_draws / n_chains) + n_warmup)
# Run all models and calculate Bayes factors comparing to full model
set.seed(101)
bayes_full_pilot <- brm(correct ~ condition + condition_order + trial_num_z + sex + age_z + training_score_z + (condition_c + trial_num_z || subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
bayes_nocondition_pilot <- brm(correct ~ condition_order + trial_num_z + sex + age_z + training_score_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(condition_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_nocondition_pilot, repetitions = 10, silent = TRUE))
bayes_noconditionorder_pilot <- brm(correct ~ condition + trial_num_z + sex + age_z + training_score_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(order_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_noconditionorder_pilot, repetitions = 10, silent = TRUE))
bayes_notrialnum_pilot <- brm(correct ~ condition + condition_order + sex + age_z + training_score_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(trialnum_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_notrialnum_pilot, repetitions = 10, silent = TRUE))
bayes_nosex_pilot <- brm(correct ~ condition + condition_order + trial_num_z + age_z + training_score_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(sex_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_nosex_pilot, repetitions = 10, silent = TRUE))
bayes_noage_pilot <- brm(correct ~ condition + condition_order + trial_num_z + sex + training_score_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(age_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_noage_pilot, repetitions = 10, silent = TRUE))
bayes_notraining_pilot <- brm(correct ~ condition + condition_order + trial_num_z + sex + age_z + (condition_c + trial_num_z | subjectID), family = bernoulli, data = model_data_pilot,
save_pars = save_pars(all = TRUE), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf))
(training_bf_pilot <- bayes_factor(bayes_full_pilot, bayes_notraining_pilot, repetitions = 10, silent = TRUE))
# Create table of Bayes factors
model_bfs_pilot <- tibble(effect = c("(Intercept)", "Condition", "Condition order", "Trial number", "Sex", "Age", "Training score"), bf = c(NA, condition_bf_pilot$bf_median_based, order_bf_pilot$bf_median_based, trialnum_bf_pilot$bf_median_based, sex_bf_pilot$bf_median_based, age_bf_pilot$bf_median_based, training_bf_pilot$bf_median_based))
write_csv(model_bfs_pilot, here("results/md1_model_bfs_pilot.csv"))
```
```{r build-model-table-pilot}
# Build model table for pilot data
# Read in model tables to save time
full_model_table_pilot <- read_csv(here("results/md1_full_model_pilot.csv"), show_col_types = FALSE)
drop1_full_model_pilot <- read_csv(here("results/md1_drop_model_pilot.csv"), show_col_types = FALSE)
model_bfs_pilot <- read_csv(here("results/md1_model_bfs_pilot.csv"), show_col_types = FALSE)
model_cis_pilot <- read_csv(here("results/md1_ci_model_pilot.csv"), show_col_types = FALSE)
# Clean and standardize effects for combining tables
full_model_trimmed_pilot <- clean_effects(full_model_table_pilot)
model_cis_trimmed_pilot <- clean_effects(model_cis_pilot)
drop1_full_model_trimmed_pilot <- drop1_full_model_pilot |>
clean_effects()
# Create table
model_table_pilot <- full_model_trimmed_pilot |>
left_join(model_cis_trimmed_pilot, by = "effect") |>
left_join(drop1_full_model_trimmed_pilot, by = "effect") |>
left_join(model_bfs_pilot, by = "effect") |>
select(effect, Estimate, SE = `Std. Error`, `Lower CI` = X2.5., `Upper CI` = X97.5.,
`Chi-square` = LRT, df = npar, p = `Pr(Chi)`, `BF` = bf) |>
mutate(across(c(-df, -effect), ~ format_num(.x, digits = 2)),
across(`Chi-square`:BF, ~ str_replace(.x, " NA", "")),
across(df, ~ str_replace_na(.x, ""))) |>
remove_rownames()
```
```{r condition-plot-pilot, include = FALSE}
# Create condition plots for pilot data
# Calculate within-subject confidence intervals for plot
ci_data_pilot <- summary(wsci(data = agg_data_pilot, id = "subjectID", factors = c("condition"), dv = "mean_correct")) |>
mutate(cond_num = case_when(condition == "nonostensive" ~ 1,
condition == "ostensive" ~ 2,
condition == "odor" ~ 3,
.default = NA))
# Ostensive/non-ostensive plot
condition_plot_pilot <- agg_data_noodor_pilot |>
ggplot(aes(x = condition, y = mean_correct)) +
geom_line(aes(x = cond_jitter, group = subjectID),
color = "gray", alpha = 0.25) +
geom_point(data = agg_data_nonostensive_pilot,
aes(x = cond_jitter),
color = "#0072B2", size = 1.5, alpha = 0.25) +
geom_point(data = agg_data_ostensive_pilot,
aes(x = cond_jitter),
color = "#D55E00", size = 1.5, alpha = 0.25, ) +
geom_half_violin(data = agg_data_nonostensive_pilot,
aes(x = cond_num, y = mean_correct),
position = position_nudge(x = -0.25), side = "l", fill = "#0072B2", alpha = 0.5) +
geom_half_violin(data = agg_data_ostensive_pilot,
aes(x = cond_num, y = mean_correct),
position = position_nudge(x = 0.25), side = "r", fill = "#D55E00", alpha = 0.5) +
geom_hline(yintercept = 0.5, lty = 2, col = "firebrick") +
geom_pointrange(data = ci_data_pilot |> filter(condition != "odor"),
aes(x = cond_num, y = mean, ymin = lower_limit, ymax = upper_limit),
color = "black", size = 0.15, linewidth = 0.6) +
geom_line(data = ci_data_pilot |> filter(condition != "odor"),
aes(x = cond_num, y = mean), color = "black") +
xlab("Condition") +
ylab("Proportion correct") +
scale_x_continuous(breaks = c(1, 2), labels = c("Non-ostensive", "Ostensive")) +
ylim(0, 1) +
theme_classic() +
theme(text = element_text(family = "Arial")
)
# Odor control
odor_plot_pilot <- ggplot(data = agg_data_odor_pilot, aes(x = as.numeric(condition), y = mean_correct)) +
geom_jitter(data = agg_data_odor_pilot, aes(x = as.numeric(condition)),
color = "grey", size = 1.5, alpha = 0.5, height = 0, width = 0.2) +
geom_half_violin(data = agg_data_odor_pilot, aes(x = as.numeric(condition), y = mean_correct),
position = position_nudge(x = -0.3), side = "l", width = 0.2, fill = "grey", alpha = .5) +
geom_hline(yintercept = 0.5, lty = 2, col = "firebrick") +
geom_pointrange(data = ci_data_pilot |> filter(condition == "odor"),
aes(y = mean, ymin = lower_limit, ymax = upper_limit),
color = "grey50", size = 0.15, linewidth = 0.6) +
xlab("") +
ylab("Proportion correct") +
scale_x_continuous(breaks = c(2), labels = c("Odor Control"), limits = c(1.5, 2.3)) +
ylim(0, 1) +
theme_classic() +
theme(text = element_text(family = "Arial")
)
# Combine plots
condition_plot_pilot + odor_plot_pilot +
plot_layout(widths = c(2, 1)) +
plot_annotation(tag_levels = "A", tag_prefix = "(", tag_suffix = ")")
ggsave(here("figures/md1_conditions_pilot.png"), width = 10, height = 8, scale = 0.5)
```
The dogs choose the baited cup more in the Ostensive condition compared to the Non-ostensive condition (_X_^2^(`r model_table_pilot[model_table_pilot$effect == "Condition", "df"]`) = `r printnum(model_table_pilot[model_table_pilot$effect == "Condition", "Chi-square"])`, _p_ = `r printnum(model_table_pilot[model_table_pilot$effect == "Condition", "p"])`, _BF_~10~ = `r printnum(model_table_pilot[model_table_pilot$effect == "Condition", "BF"], digits = 1)`) (Figure S6A). None of the control predictors (order of condition, trial number within condition, sex, age, C-BARQ trainability score) had any effect on dogs' choices (Table S2).
```{r check-assumptions-pilot, eval = FALSE, include = FALSE}
# Check assumptions and model stability for pilot data
# Plot visualizations of model checks
check_model(full_model_pilot)
# Check for collinearity
check_collinear <- lm(correct ~ condition + condition_order + trial_num_z +
sex + desexed + age_z + training_score_z,
data = model_data_pilot)
vif(check_collinear)
# Collinearity was no issue (maximum variance inflation factor: 1.11)
## Model stability
## One subject at a time excluded to assess the impact of outliers.
# model_stability_md1_subj <- glmm.model.stab(model.res = full_model_pilot, use = c("subjectID"), para = TRUE, n.cores = n_cpu_ci)
# model_stability_md1_subj$detailed$warnings
# model_stability_md1_subj_warnings <- as.data.frame(round(model_stability_md1_subj$summary[, -1], 3))[1:9,]
# png("figures/md1_full_model_stability_plot_subj.png")
# m.stab.plot(round(model_stability_md1_subj$summary[, -1], 3)[1:9,])
# dev.off()
## One site at a time excluded to assess the impact of outliers.
# model_stability_md1_site <- glmm.model.stab(model.res = full_model_pilot, use = c("site"), para = TRUE, n.cores = n_cpu_ci)
# model_stability_md1_site$detailed$warnings
# png("figures/md1_full_model_stability_plot_site.png")
# m.stab.plot(round(model_stability_md1_site$summary[, -1], 3)[1:9,])
# dev.off()
# The model appeared to be stable with respect to the fixed effects (see full_model_stability_plot_site and full_model_stability_plot_subject).
```
## Main experiment
\setcounter{figure}{3}
### _Demographics_
```{r site-information}
# Build table of site information
site_name <- c("Animal Health and Welfare Research Centre",
"Arizona Canine Cognition Center",
"Auburn Canine Performance Sciences",
"Boston Canine Cognition Center",
"Brown Dog Lab",
"Canid Behavior Research Group",
"Canine Cognition and Human Interaction Lab",
"Canine Cognition Center at Yale",
"Canine Companions",
"Canine Research Unit",
"Clever Dog Lab$^{\\dagger}$",
"Comparative Cognition Lab",
"Comparative Cognitive Science Lab",
"Consultorio Comportamentale",
"Department of Psychology and Individual Differences",
"Dog Cognition Centre",
"Duke Canine Cognition Center",
"Leader Dogs for the Blind$^{\\ddagger}$",
"Social Cognition Lab",
"The Family Dog Project",
"Thinking Dog Center")
site <- c("ucs", "accc", "auburn", "bccc", "bdl", "icoc", "cchil", "yale", "cci", "crumun", "cdl", "manitoba", "urijeka", "umessina", "uwarsaw", "dcc", "duke", "ldbtdc", "queensu", "eltebuda", "tdc")
site_abbr <- c("AHWRC", "ACCC", "ACPS", "BCCC", "BDL", "CBRG", "CCHIL", "CCC", "CCI", "CRU", "CDL", "CCL", "CCSL", "CC", "DPID", "DCC", "DCCC", "LDB", "SCL", "TFDP", "TDC")
lead <- c("Marianne Freeman", "Evan MacLean", "Lucia Lazarowski", "Angie Johnston", "Daphna Buchsbaum", "Mariana Bentosela", "Jeffrey Stevens", "Laurie Santos", "Brenda Kennedy", "Carolyn Walsh", "Ludwig Huber", "Debbie Kelly", "Ljerka Ostoji\'{c}", "Daniela Alberghina", "Anna Reinholz", "Juliane Kaminski", "Brian Hare", "Sarah-Elizabeth Byosiere", "Valerie Kuhlmeier", "Ádám Miklósi", "Sarah-Elizabeth Byosiere")
lead <- c("Marianne Freeman", "Evan MacLean", "Lucia Lazarowski", "Angie Johnston", "Daphna Buchsbaum", "Camila Cavalli", "Jeffrey Stevens", "Laurie Santos", "Emily Bray", "Carolyn Walsh", "Ludwig Huber", "Debbie Kelly", "Ljerka Ostojić", "Daniela Alberghina", "Anna Reinholz", "Juliane Kaminski", "Brian Hare", "Sarah-Elizabeth Byosiere", "Valerie Kuhlmeier", "Andrea Sommese", "Sarah-Elizabeth Byosiere")
location <- c("Winchester, United Kingdom", "Tuscon, AZ, USA", "Auburn, AL, USA", "Boston, MA, USA", "Providence, RI, USA", "Buenos Aires, Argentina", "Lincoln, NE, USA", "New Haven, CT, USA", "Santa Rosa, CA, USA", "St. John’s, NL, Canada", "Vienna, Austria", "Winnipeg, MB, Canada", "Rijeka, Croatia", "Messina, Italy", "Warsaw, Poland", "Portsmouth, United Kingdom", "Durham, NC, USA", "Rochester, MI, USA", "Dundalk, ON, Canada", "Budapest, Hungary", "New York City, NY, USA")
team <- c(2, 3, 3, 3, 4, 3, 5, 3, 3, 3, 3, 3, 2, 2, 4, 5, 3, 2, 2, 3, 3)
testing <- c("Lab", "Lab", "Lab, Facility", "Lab", "Lab", "Home", "Lab", "Lab", "Facility", "Lab", "Lab", "Lab", "Lab", "Lab", "Lab", "Lab", "Lab", "Facility", "Lab, Facility", "Lab", "Lab")
site_info <- data.frame(site_name, site, site_abbr, lead, location, team, testing) |>
filter(site != "cdl")
site_key <- select(site_info, site, site_abbr)
cdl_info <- data.frame(site_name = "Clever Dog Lab$^{\\dagger}$", site = "cdl",
site_abbr = "CDL", lead = "Ludwig Huber",
location = "Vienna, Austria", team = 3, testing = "Lab",
n = 61, age_mean = 5.13, age_sd = 3.31, age_min = 1,
age_max = 12, sex_female = 61-26, sex_male = 26,
desexed_no = 36, desexed_yes = 25, purebred_no = 1,
purebred_yes = 60, owned_status_group = 0,
owned_status_other = 0, owned_status_private = 61)
```
```{r import-data}
# Import data and separate included data
all_data <- read_csv(here("md1_data.csv"), show_col_types = FALSE) |>
left_join(site_key, by = "site") |>
select(site_abbr, everything(), -site) |>
rename(site = site_abbr) |>
mutate(owned_status = fct_recode(owned_status, private = "Private home",
group = "Group housing (e.g., working dog kennel)",
other = "Other"),
owned_status = as.character(owned_status))
included_data <- all_data |>
filter(status == "Included" & !grepl("cup", condition) & valid_trial <= 8) |>
mutate(condition = ifelse(is.na(condition), condition, condition))
```
```{r demographics}
# Calculate demographic information
# All data
demographics_all <- all_data |>
group_by(subjectID) |>
slice_head() |>
ungroup()
demographics_measures <- c("age", "sex", "desexed", "purebred", "owned_status", "status")
demographics_all_overall <- map_dfc(demographics_measures,
~ calculate_site_demographics(demographics_all, .data[[.x]]),
overall = TRUE) |>
mutate(site = "Overall", .before = 1)
demographics_all_site <- map_dfc(demographics_measures,
~ calculate_site_demographics(demographics_all, .data[[.x]],
overall = FALSE)) |>
select(-contains("_site"))
demographics_all_summary <- bind_rows(demographics_all_overall, demographics_all_site)
# Included data demographics
demographics_included <- included_data |>
group_by(subjectID) |>
slice_head() |>
ungroup()
demographics_included_overall <- map_dfc(demographics_measures[-length(demographics_measures)],
~ calculate_site_demographics(demographics_included, .data[[.x]]),
overall = TRUE) |>
mutate(site = "Overall", .before = 1)
demographics_included_site <- map_dfc(demographics_measures[-length(demographics_measures)],
~ calculate_site_demographics(demographics_included, .data[[.x]],
overall = FALSE)) |>
select(-contains("_site"))
demographics_included_summary <- bind_rows(demographics_included_site,
demographics_included_overall) |>
mutate(across(age_mean:age_sd, ~round(.x, 1)))
```
Across `r nrow(demographics_all_site)` sites, we tested `r demographics_all_overall$n` dogs and received demographic information for `r demographics_all_overall$n - 3` of them (M:F = `r demographics_all_overall$sex_male`:`r demographics_all_overall$sex_female`, mean±SD age = `r round(demographics_all_overall$age_mean, 1)`±`r round(demographics_all_overall$age_sd, 1)` years [range = `r demographics_all_overall$age_min`-`r demographics_all_overall$age_max`]). Approximately `r round(demographics_all_overall$desexed_yes / (demographics_all_overall$desexed_yes + demographics_all_overall$desexed_no) * 100, 1)`% of the dogs were spayed or neutered, `r round(demographics_all_overall$purebred_yes / (demographics_all_overall$purebred_yes + demographics_all_overall$purebred_no) * 100, 1)`% were purebred, and `r round(demographics_all_overall$owned_status_private / (demographics_all_overall$owned_status_private + demographics_all_overall$owned_status_group + demographics_all_overall$owned_status_other) * 100, 1)`% lived in private homes, `r round(demographics_all_overall$owned_status_group / (demographics_all_overall$owned_status_private + demographics_all_overall$owned_status_group + demographics_all_overall$owned_status_other) * 100, 1)`% lived in group/kennel housing, and `r round(demographics_all_overall$owned_status_other / (demographics_all_overall$owned_status_private + demographics_all_overall$owned_status_group + demographics_all_overall$owned_status_other) * 100, 1)`% lived in other housing (Table S1). However, `r (demographics_all_overall$status_incomplete + demographics_all_overall$status_error)` dogs were excluded from the analysis because they failed to meet the inclusion criteria (`r demographics_all_overall$status_incomplete` failed to complete all trials and `r demographics_all_overall$status_error` experienced experimental errors during their sessions). This left `r demographics_all_overall$status_included` dogs for our analysis (M:F = `r demographics_included_overall$sex_male`:`r demographics_included_overall$sex_female`, mean±SD age = `r round(demographics_included_overall$age_mean, 1)`±`r round(demographics_included_overall$age_sd, 1)` years [range = `r demographics_included_overall$age_min`-`r demographics_included_overall$age_max`]).
```{r breed-info}
# Find number of each breed
breeds <- included_data |>
filter(status == "Included") |>
group_by(subjectID) |>
slice_head(n = 1) |>
ungroup() |>
count(breed) |>
drop_na() |>
arrange(desc(n))
n_breeds <- nrow(filter(breeds, n >= 8))
```
### _Inter-Rater Reliability_
```{r reliability}
# Calculate inter-rater reliability
sites <- unique(included_data$site)
overall_reliability_kappa <- cohen.kappa(cbind(included_data$choice, included_data$recoded_choice))
site_reliablity <- map(sites, calculate_site_reliability)
names(site_reliablity) <- sites
site_kappas <- unlist(lapply(site_reliablity, "[[", 2))
```
The raters who recoded a subset of the trials had very high reliability with the original coding for choice ($\kappa$ = `r apa_num(overall_reliability_kappa$kappa)`, 95% CI [`r apa_num(overall_reliability_kappa$confid[1])`, `r apa_num(overall_reliability_kappa$confid[5])`], N = `r overall_reliability_kappa$n.obs`). Individual site reliability ranged from $\kappa$ = `r format_num(min(site_kappas), digits = 2)`-`r format_num(max(site_kappas), digits = 2)`.
```{r aggregate-data}
agg_data <- included_data |>
group_by(site, subjectID, sex, breed, breed_group, age, training, condition) |>
summarise(mean_correct = mean(correct, na.rm = TRUE), .groups = "drop")
n_subjects <- agg_data |>
slice_head(by = subjectID) |>
nrow()
agg_data_noodor <- agg_data |>
filter(condition != "odor") |>
mutate(cond_jitter = jitter(as.numeric(as.factor(condition)), amount = 0.1),
cond_num = case_when(condition == "nonostensive" ~ 1,
condition == "ostensive" ~ 2,
.default = NA))
agg_data_ostensive <- agg_data_noodor |>
filter(condition == "ostensive")
agg_data_nonostensive <- agg_data_noodor |>
filter(condition == "nonostensive")
agg_data_odor <- agg_data |>
mutate(condition=as.factor(condition))|>
filter(condition == "odor")
```
### _Confirmatory Analyses_
#### _Performance Relative to Chance_
```{r t-tests}
# Calculate one-sample t-tests for each condition overall and for each site
overall_ttests <- calculate_ttests()
for(i in seq_along(overall_ttests)) assign(names(overall_ttests)[i], overall_ttests[[i]])
sites <- unique(agg_data$site)
site_ttests <- map(sites, calculate_ttests)
names(site_ttests) <- sites
site_nas <- rep(NA, length(sites))
site_ttests_df <- data.frame(site = sites, tt_ost_p = site_nas,
tt_nonost_p = site_nas, tt_odor_p = site_nas,
tt_ost = site_nas, tt_nonost = site_nas,
tt_odor = site_nas)
for(i in seq_along(site_ttests)) {
site_ttests_df$tt_ost_p[i] <- site_ttests[[i]]$tt_ost$p.value
site_ttests_df$tt_nonost_p[i] <- site_ttests[[i]]$tt_nonost$p.value
site_ttests_df$tt_odor_p[i] <- site_ttests[[i]]$tt_odor$p.value
site_ttests_df$tt_ost[i] = paste0(apa_print(site_ttests[[i]]$tt_ost)$full_result, ", ",
apa_print(site_ttests[[i]]$tt_ost_bf)$statistic)
site_ttests_df$tt_nonost[i] = paste0(apa_print(site_ttests[[i]]$tt_nonost)$full_result, ", ",
apa_print(site_ttests[[i]]$tt_nonost_bf)$statistic)
site_ttests_df$tt_odor[i] = paste0(apa_print(site_ttests[[i]]$tt_odor)$full_result, ", ",
apa_print(site_ttests[[i]]$tt_odor_bf)$statistic)
}
# Find number of sites with p < 0.05
n_ost_sites <- sum(site_ttests_df$tt_ost_p < 0.05)
n_nonost_sites <- sum(site_ttests_df$tt_nonost_p < 0.05)
n_odor_sites <- sum(site_ttests_df$tt_odor_p < 0.05)
```
The dogs (N = `r n_subjects`) performed better than expected by chance in the Ostensive condition (`r apa_ttest(tt_ost, digits = 2)`, `r format_bf(tt_ost_bf)`) and in the Non-ostensive condition (`r apa_ttest(tt_nonost, digits = 2)`, `r format_bf(tt_nonost_bf)`) but not in the Odor Control condition (`r apa_ttest(tt_odor, digits = 2)`, `r format_bf(tt_odor_bf)`) (Figure \@ref(fig:cond-chance)). Mean performance in all conditions at individual sites typically did not differ from chance with a few exceptions: `r make_word_nums(n_ost_sites)` sites had Ostensive performance greater than chance, `r make_word_nums(n_nonost_sites)` sites had Non-ostensive performance greater than chance (Table S3).
#### _Condition Comparison_
```{r model-building}
# Build models
# Center and scale variables for modeling
model_data <- included_data |>
filter(condition == "ostensive" | condition == "nonostensive") |>
mutate(
age_z = as.numeric(scale(age, scale = TRUE, center = TRUE)),
trial_num_z = as.numeric(scale(valid_trial, scale = TRUE, center = TRUE)),
trainability_score_z = as.numeric(scale(training, scale = TRUE,
center = TRUE)),
condition_c = as.numeric(scale(as.numeric(as.factor(condition)),
scale = FALSE, center = TRUE)),
condition_order_c = as.numeric(scale(as.numeric(as.factor(condition_order)),
scale = FALSE, center = TRUE)),
sex_c = as.numeric(scale(as.numeric(as.factor(sex)), scale = FALSE,
center = TRUE)),
desexed_c = as.numeric(scale(as.numeric(as.factor(desexed)), scale = FALSE,
center = TRUE))
)
# Define full models (with and without correlations in random effects)
fixed_effects <- "correct ~ condition + condition_order + trial_num_z + sex*desexed + age_z + trainability_score_z +"
random_effects_corr <- "(condition_c + trial_num_z | subjectID) + (condition_c + condition_order_c + trial_num_z + sex_c*desexed_c + age_z + trainability_score_z | site)"
random_effects_nocorr <- "(condition_c + trial_num_z || subjectID) + (condition_c + condition_order_c + trial_num_z + sex_c*desexed_c + age_z + trainability_score_z || site)"
full_model_formula_corr <- paste(fixed_effects, random_effects_corr)
full_model_formula_nocorr <- paste(fixed_effects, random_effects_nocorr)
```
```{r run-model, eval = FALSE, include = FALSE}
# Run the full models with and without correlations
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
# Set model control parameters and random seed
contr <- glmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 10000000), calc.derivs = FALSE)
set.seed(100)
# Run full models (with and without correlations)
full_model_corr <- glmer(full_model_formula_corr, family = binomial,
data = model_data, control = contr, nAGQ = 0)
full_model_nocorr <- glmer(full_model_formula_nocorr, family = binomial,
data = model_data, control = contr, nAGQ = 0)
# Compare models
summary(full_model_corr)$log
summary(full_model_nocorr)$log
# Model with no correlations has better fit (lower log-likelihood), so use that model
# Set effects and build model formula
random_effects <- random_effects_nocorr
full_model_formula <- full_model_formula_nocorr
full_model <- full_model_nocorr
full_model_table <- as.data.frame(summary(full_model)$coefficients) |>
rownames_to_column(var = "effect_full")
write_csv(full_model_table, here("results/md1_full_model.csv"))
## Calculate likelihood ratio test
drop1_full_model <- drop1(full_model, test = "Chisq", control = contr)
drop1_full_model_rownames <- rownames(drop1_full_model)
drop1_full_model_table <- tibble(effect_drop = drop1_full_model_rownames, drop1_full_model)
write_csv(drop1_full_model_table, here("results/md1_drop_model.csv"))
```
```{r bootstrap-cis, eval = FALSE, include = FALSE}
# Calculate bootstrapped 95% confidence intervals for model estimates
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
set.seed(300)
full_model2 <- glmer(full_model_formula, family = binomial, data = model_data,
control = glmerControl(optimizer = "bobyqa",
optCtrl = list(maxfun = 10000000),
calc.derivs = FALSE), nAGQ = 0)
full_model_ci <- boot.glmm.pred(model.res = full_model2, excl.warnings = TRUE,
nboots = 1000, para = TRUE, n.cores = n_cpu_ci,
level = 0.95)
full_model_ci_estimates<-full_model_ci$ci.estimates
full_model_ci_estimatesl_rownames <- rownames(full_model_ci_estimates)
full_model_ci_estimates_table <- tibble(effect_ci = full_model_ci_estimatesl_rownames, full_model_ci_estimates)
write_csv(full_model_ci_estimates_table, here("results/md1_ci_model.csv"))
```
```{r bayes-factors, eval = FALSE, include = FALSE}
# Run the full Bayesian models with and without correlations for pilot data
# Output is saved locally to save time, so this code chunk is not evaluated during knitting
# Prepare computing environment for Bayesian analysis
n_chains <- 4L
total_draws <- 40000
n_warmup <- 5000
n_iter <- round((total_draws / n_chains) + n_warmup)
# Run all models
set.seed(101)
prior <- prior(student_t(6, 0, 1.5))
full_model_bayes <- brm(full_model_formula, data = model_data, family = bernoulli,
prior = prior, sample_prior = "yes",
control = list(adapt_delta = 0.9), backend = "cmdstanr",
iter = n_iter, warmup = n_warmup,
chains = n_chains, cores = n_cpu_bf,
threads = threading(n_threads_bf),
seed = 101, silent = 2
)
# Calculate Bayes factors by testing hypotheses of estimates = 0
bfs <- 1 / hypothesis(full_model_bayes, c("conditionostensive = 0",
"condition_orderost_first = 0",
"trial_num_z = 0",
"sexMale:desexedYes = 0",
"age_z = 0",
"trainability_score_z = 0"))$hypothesis$Evid.Ratio
model_bfs <- tibble(effect = c("(Intercept)", "Condition", "Condition order", "Trial number", "Sex:desexed", "Age", "Trainability score"), bf = c(NA, bfs))
write_csv(model_bfs, here("results/md1_model_bfs.csv"))
```
```{r build-model-table}
# Build model table
# Read in model tables to save time
full_model_table <- read_csv(here("results/md1_full_model.csv"), show_col_types = FALSE)
drop1_full_model <- read_csv(here("results/md1_drop_model.csv"), show_col_types = FALSE)
model_bfs <- read_csv(here("results/md1_model_bfs.csv"), show_col_types = FALSE)
model_cis <- read_csv(here("results/md1_ci_model.csv"), show_col_types = FALSE)
# Clean and standardize effects for combining tables
full_model_trimmed <- clean_effects(full_model_table)
model_cis_trimmed <- clean_effects(model_cis)
drop1_full_model_trimmed <- drop1_full_model |>
clean_effects()
# Create table
model_table <- full_model_trimmed |>
left_join(model_cis_trimmed, by = "effect") |>
left_join(drop1_full_model_trimmed, by = "effect") |>
left_join(model_bfs, by = "effect") |>
select(effect, Estimate, SE = `Std. Error`, `Lower CI` = X2.5., `Upper CI` = X97.5.,
`Chi-square` = LRT, df = npar, p = `Pr(Chi)`, `BF` = bf) |>
mutate(across(where(is.numeric), ~ round(.x, 2))) |>
remove_rownames()
```
```{r condition-plot, include = FALSE}
# Create overall condition plots
# Calculate within-subject confidence intervals for plot
ci_data <- summary(wsci(data = agg_data, id = "subjectID", factors = c("condition"), dv = "mean_correct")) |>
mutate(cond_num = case_when(condition == "nonostensive" ~ 1,
condition == "ostensive" ~ 2,
condition == "odor" ~ 3,
.default = NA))
# Ostensive/non-ostensive plot
condition_plot <- agg_data_noodor |>
ggplot(aes(x = condition, y = mean_correct)) +
geom_line(aes(x = cond_jitter, group = subjectID),
color = "gray", alpha = 0.25) +
geom_point(data = agg_data_nonostensive,
aes(x = cond_jitter),
color = "#0072B2", size = 1.5, alpha = 0.25) +
geom_point(data = agg_data_ostensive,
aes(x = cond_jitter),
color = "#D55E00", size = 1.5, alpha = 0.25, ) +
geom_half_violin(data = agg_data_nonostensive,
aes(x = cond_num, y = mean_correct),
position = position_nudge(x = -0.25), side = "l", fill = "#0072B2", alpha = 0.5) +
geom_half_violin(data = agg_data_ostensive,
aes(x = cond_num, y = mean_correct),
position = position_nudge(x = 0.25), side = "r", fill = "#D55E00", alpha = 0.5) +
geom_pointrange(data = ci_data |> filter(condition != "odor"),
aes(x = cond_num, y = mean, ymin = lower_limit, ymax = upper_limit),
color = "black", size = 0.15, linewidth = 0.6) +
geom_line(data = ci_data |> filter(condition != "odor"),
aes(x = cond_num, y = mean), color = "black") +
geom_hline(yintercept = 0.5, lty = 2, col = "firebrick") +
xlab("Condition") +
ylab("Proportion correct") +
scale_x_continuous(breaks = c(1, 2), labels = c("Non-ostensive", "Ostensive")) +
ylim(0, 1) +
theme_classic() +
theme(text = element_text(family = "Arial")
)
# Odor control
odor_plot <- ggplot(data = agg_data_odor, aes(x = as.numeric(condition), y = mean_correct)) +
geom_jitter(data = agg_data_odor, aes(x = as.numeric(condition)),
color = "grey", size = 1.5, alpha = 0.5, height = 0, width = 0.2) +
geom_half_violin(data = agg_data_odor, aes(x = as.numeric(condition), y = mean_correct),
position = position_nudge(x = -0.3), side = "l", width = 0.2, fill = "grey", alpha = .5) +
geom_hline(yintercept = 0.5, lty = 2, col = "firebrick") +
geom_pointrange(data = ci_data |> filter(condition == "odor"),
aes(y = mean, ymin = lower_limit, ymax = upper_limit),
color = "grey50", size = 0.15, linewidth = 0.6) +
xlab("") +
ylab("Proportion correct") +
scale_x_continuous(breaks = c(2), labels = c("Odor Control"), limits = c(1.5, 2.3)) +
ylim(0, 1) +
theme_classic() +
theme(text = element_text(family = "Arial")
)
# Combine plots
condition_plot + odor_plot +
plot_layout(widths = c(2, 1)) +
plot_annotation(tag_levels = "A", tag_prefix = "(", tag_suffix = ")")
ggsave(here("figures/md1_conditions.png"), width = 10, height = 8, scale = 0.5)
```
```{r site-comparison}
# Create site-specific condition plots
# Calculate within-subject confidence intervals for plot
ci_data_site <- summary(wsci(data = agg_data, id = "subjectID", factors = c("site", "condition"), dv = "mean_correct")) |>
mutate(cond_x = if_else(condition == "nonostensive", 1, 2, NA))
# Calculate t-tests
site_results <- data.frame(site = sites, results = unlist(map(sites, ost_nonost_ttests)))
agg_data_noodor2 <- agg_data_noodor |>
left_join(site_results, by = "site")
# Ostensive/non-ostensive plot
site_condition_plot <- ggplot(data = agg_data_noodor, aes(x = condition, y = mean_correct)) +
geom_line(aes(x = cond_num, group = subjectID), color = "gray", alpha = 0.25) +
geom_point(data = agg_data_noodor |> filter(condition == "nonostensive"),
aes(x = cond_num), color = "#0072B2", size = 1.5, alpha = 0.125) +
geom_point(data = agg_data_noodor |> filter(condition == "ostensive"),