Repository navigation
Expand file tree
/
Copy pathg_exploration.Rmd
More file actions
3185 lines (2408 loc) · 255 KB
/
Copy pathg_exploration.Rmd
File metadata and controls
3185 lines (2408 loc) · 255 KB
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: Behavioral flexibility is related to exploration, but not boldness, persistence
or motor diversity
author:
- '[McCune KB](https://www.kelseymccune.com)^1,2^'
- Lukas D^3^
- MacPherson M^1,4^
- '[Logan CJ](http://CorinaLogan.com)^3^'
date: "`r Sys.Date()`"
output:
pdf_document:
keep_tex: true
latex_engine: xelatex
md_document:
toc: true
html_document:
toc: true
toc_depth: 4
toc_float:
collapsed: false
code_folding: hide
github_document:
toc: true
word_document:
toc: true
toc_depth: '4'
bibliography: MyLibrary.bib
csl: "Peer-Community-Journal-PCI.csl"
header-includes: \usepackage[left]{lineno}
---
```{r, include=FALSE}
options(tinytex.verbose = TRUE)
```
```{r setup, include=FALSE}
library(knitr)
library(formatR)
knitr::opts_chunk$set(tidy.opts=list(width.cutoff=70),tidy=TRUE)
#Make code chunks wrap text so it doesn't go off the page when knitting to PDF
knitr::opts_chunk$set(echo=F, include=T, results='asis', warning=F, message=F)
#sets global options to display code along with the results https://exeter-data-analytics.github.io/LitProg/r-markdown.html
#set echo=F for knitting to PDF (hide code), and echo=T for knitting to HTML (show code)
options(xtable.comment = FALSE) #makes it so a note about how the table was printed doesn't show up in the pdf
```
[](https://doi.org/10.24072/pci.ecology.100771)
##### Affiliations:
1) Institute for Social, Behavioral and Economic Research, University of California Santa Barbara, USA
2) College of Forestry, Wildlife and Environment, Auburn University, USA
3) Department of Human Behavior, Ecology and Culture, Max Planck Institute for Evolutionary Anthropology, Germany
4) Department of Biology, Trent University, Canada
5) Neuroscience Research Institute, University of California Santa Barbara, UUSA
*Corresponding author: kelseybmccune@gmail.com
**This is the post-study manuscript of the preregistration that was pre-study peer reviewed and received an In Principle Recommendation on 27 March 2019 by:**
Jeremy Van Cleve (2019) Probing behaviors correlated with behavioral flexibility. *Peer Community in Ecology*, 100020. [10.24072/pci.ecology.100020](https://ecology.peercommunityin.org/public/rec?id=29&reviews=True). Reviewers: two anonymous reviewers. The **Preregistration** is available as an [html](http://corinalogan.com/Preregistrations/g_exploration.html), [pdf](https://github.com/corinalogan/grackles/blob/master/Files/Preregistrations/g_explorationPassedPreStudyPeerReviewOn27Mar2019.pdf), or in [R markdown with code](https://github.com/corinalogan/grackles/blob/d17a75c24df4b90aa607eda452f4fcc496ae9409/Files/Preregistrations/g_exploration.Rmd).
The **Post-study manuscript** was submitted to PCI Ecology for post-study peer review on 11 November 2024. We received reviewer comments on 3 January 2025. We revised and resubmitted to PCI Ecology on 1 April 2025.
**This research article is now recommended by:** Jeremy Van Cleve (2025). Exploring exploration and behavioral flexibility in grackles: how to handle issues of "jingle-jangle" and repeatability. [*Peer Community in Ecology*, 100771](https://doi.org/10.24072/pci.ecology.100771). Reviewers: two anonymous reviewers. The manuscript is available at [EcoEvoRxiv](https://ecoevorxiv.org/repository/view/8045/) and the data and code are available at [KNB Repository](https://knb.ecoinformatics.org/view/doi:10.5063/F118350Q).
# Abstract {-}
Behavioral flexibility, the ability to change behavior when circumstances change based on learning from previous experience, is thought to play an important role in a species' ability to successfully adapt to new environments and expand its geographic range. However, behavioral flexibility is rarely directly tested at the individual level. This limits our ability to determine how it relates to other traits, such as exploration or persistence, that might also influence individual responses to novel circumstances. Without this information, we lack the power to predict which traits facilitate a species' ability to adapt behavior to new environments. We use great-tailed grackles (a bird species; hereafter “grackles”) as a model to investigate this question because they have rapidly expanded their range into North America over the past 140 years. We evaluated whether grackle behavioral flexibility (measured as color reversal learning) correlated with individual differences in the exploration of new environments and novel objects, boldness towards known and novel threats, as well as persistence and motor diversity in accessing a novel food source. We determined that exploration of a novel environment across two time points and persistence when interacting with several different novel apparatuses were repeatable in individual grackles. There was no relationship between exploration or persistence and the two components of flexibility - the rate of learning to prefer a color option in the reversal learning task, and the rate of deviating from a preferred option. However, grackles that underwent serial reversal training to experimentally increase behavioral flexibility were more exploratory in that they spent more time in close proximity to the novel environment relative to control individuals. This indicates that, the more an individual investigated a novel apparatus, the more it was able to potentially learn and update its knowledge of current reward contingencies to adapt behavior accordingly. Our findings improve our understanding of the traits that are linked with flexibility in a highly adaptable species. We highlight the importance of using multiple different methods for measuring boldness and exploration to evaluate consistency of performance and therefore the methodological validity. We also show a link between exploration and behavioral flexibility that could facilitate adaptation to novel environmental changes.
**Keywords:** behavioral flexibility, personality, anthropogenic change, repeatability
### [Video summary](https://youtu.be/Xd_nYV9Lj7E) [https://youtu.be/Xd_nYV9Lj7E](https://youtu.be/Xd_nYV9Lj7E)
# Introduction {-}
Humans are altering all ecosystems on the planet too rapidly for most species to evolve adaptations to survive and reproduce [@hendry2008human; @sih2013understanding]. Among other consequences, anthropogenic change can lead to a proliferation of novel habitats, foods, and predators [@sih2011evolution]. Across short timescales, individuals must adapt to this novelty through changes in behavior. Behavioral flexibility (hereafter "flexibility") is defined as the ability to use learning to functionally change behavior when circumstances change [@mikhalevich_is_2017]. As such, flexibility is thought to facilitate species resilience to anthropogenic change [@sol2013behavioural] and species invasions into novel areas [@sol2002behavioural; @wright2010behavioral].
The relationship between flexibility and adaptation to anthropogenic change is rarely directly tested at the individual level. Research studying the impact of flexibility on the success of species invasions most often uses proxies of flexibility such as species brain size, or presence of the theoretical outcomes of flexible behavior like the number of foraging innovations [@sol2002behavioural]. The few studies that have directly related environmental adaptation to flexibility through measures of reversal learning show that flexible behavior can be closely linked with the current environmental niche. For example, mountain chickadees that live in harsh, high elevation environments perform worse on reversal learning tasks relative to lower elevation, milder climate individuals [@croston2017predictably]. This suggests that individuals that have a wider range of food options and a reduced reliance on cached food in milder climates require more flexibility to switch between food types. Additionally, new evidence from great-tailed grackles shows that the more flexible individuals also demonstrate greater foraging diversity in the wild [@logan2025flexfor], and were better able to innovate solutions on a novel foraging apparatus [@logan2023flexmanippcj]. Consequently, flexibility may show variation within, as well as among, species and may affect diverse aspects of individual behavioral interactions with the environment. To better understand how flexibility might facilitate responses to novelty and resilience to anthropogenic change, it is important to directly test flexibility and relate it to other ecological and behavioral traits at the individual level.
Although behavioral flexibility has been the trait that much research has focused on to understand how behavior can impact adaptation to anthropogenic environmental changes, individual differences in other traits like exploratory tendency, boldness, persistence, or motor diversity could also play a role and correlate with behavioral flexibility [@logan2016behavioral; @sol2002behavioural]. To distinguish whether observed behavior in the wild or performance on behavioral trait assays are motivated by one or more distinct traits, it is important to measure multiple traits in the same individuals [@carter2013animal]. However, evaluation of the relationship between flexibility and other behavioral traits has produced inconsistent results [@dougherty2018linking; @logan2016behavioral]. In one well studied avian group, the Paridae, flexibility is related to exploration, which increases the likelihood of encountering fitness-enhancing resources in novel environments [@canestrelli2016bolder; @griffin2016invading]. This might imply that they are not two distinct traits, but the direction of the relationship is inconsistent across species [positive: @rojas2020exploration; negative: @amy2012worms]. Individuals approaching a potentially threatening aspect of the environment require a certain degree of boldness [@mccune2018evidence]. However, the relationship between boldness and flexibility can be positive [@titulaer2012personality], negative [@bensky2022behavioral; @bebus2016associative], or neutral [@guenther2014learning; @de2022bold]. Theoretically, persistence should inhibit flexibility because it results in perseverating on a previously rewarded behavior rather than changing to a more productive behavior for a given circumstance [@morand2022cognitive]. In contrast to persistence, motor diversity is theoretically positively correlated with flexibility because it implies that the individual has a repertoire of different behaviors it is able to choose from to match each circumstance [@diquelou2016role]. Research in squirrels supports this prediction [@chow2016practice], where the more flexible individuals were less persistent and more likely to use diverse motor behaviors. Whereas, an earlier study in great-tailed grackles using different behavioral assays found no relationship between flexibility and any other behavioral traits, including persistence and motor diversity [@logan2016behavioral].
The lack of consistent support for which behavioral traits are related (or not) to flexibility could stem from what has been called a “jingle-jangle fallacy” [@carter2013animal]. This term describes the mismatch between a trait label (like exploration) and what the method (novel environment) actually measures (could be exploration, activity, or boldness). A mismatch can occur when researchers use a single trait label for what are actually multiple distinct inherent traits (“jingle fallacy”), or if using two or more distinct labels for what is actually the same inherent trait (“jangle fallacy”). One step towards avoiding this issue is to use multiple experimental methods, as in a test battery, to measure a variety of behaviors, then assess the relationships among performance to identify which aspects of the behaviors that are measured might be driven by the same underlying trait [@shaw2017cognitive; @perals2017revisiting].
To determine whether behavior labels represent the same underlying trait, it is also important to ensure that measured performance on behavioral assays is consistent within individuals across time and context (i.e., repeatable). Inter-individual differences in performance could result from short-term variation in the external environment like social interactions or food availability or variation in internal states like hunger or stress. This plasticity is distinct from consistent individual differences in behavior across contexts stemming from genetic or developmental effects (i.e., animal personality; @duckworth2010evolution; @fidler2007drd4). If behavioral traits are heritable, multiple traits can become linked through natural selection such that individuals that show high values on one trait (e.g., flexibility), will consistently display high values on a linked trait (e.g., exploration) [@reale2007integrating; @rowe2014measuring]. It is important to know whether traits are linked because such linkage could result in limited behavioral plasticity that may alter the ability or mode of adapting to rapid environmental changes [@sih2004behavioral]. Indeed, inconsistency in the direction of the relationship between flexibility and behavioral traits in previous studies could stem from a lack of repeatability in performance on behavioral trait assays. To address whether flexibility is related to other behavioral traits, we must first assess whether our methods produce performance that is repeatable [@dingemanse2013quantifying] to validate that it is more likely to represent variation in a heritable trait.
In a previous study with a smaller sample size [@logan2016behavioral], we found no evidence for significant correlations between flexibility and the behavioral traits exploration, boldness, persistence, and motor diversity. However, this result could stem from the small sample size and lack of power to detect a relationship with a small effect size, or methods that do not result in repeatable performance. Based on this preliminary evidence, in the present study we increased our power to detect a relationship by training some individuals to be more flexible before measuring the other behavioral traits. Additionally, we tested whether performance on measures of exploration, boldness, persistence, and motor diversity are repeatable across time and contexts and therefore likely represent distinct personality traits. Behavior is considered repeatable if the variance in performance on the task is smaller within individuals compared to the variance among individuals. If there is no repeatability of these behaviors within individuals, then performance is likely state dependent (i.e., it depends on fluctuating motivation, stress, hunger levels, etc.) and/or is reliant on the current context of the tasks, and therefore less likely to consistently correlate with flexibility [@griffin2015cognition]. Then, we assessed whether the repeatable traits were related to performance on a flexibility task. We focus on great-tailed grackles (*Quiscalus mexicanus*; hereafter “grackles”) because they are likely to have experienced selection for behavioral adaptations to rapid environmental change. Grackles have rapidly expanded their range into novel areas in North America over the past 140 years [@wehtje2003range; @summers2023xpop] and our previous research on this species has demonstrated that grackles are flexible [@logan2016flexibilityproblem], and that flexibility is a distinct trait on which grackles show individual variation [@mccune2023flexmanippeerj]. Thus, this species is ideal for assessing whether flexibility is part of a suite of behaviors that facilitate adaptation to novel environments.
## Preregistered hypotheses and predictions summary
*We preregistered several additional predictions pertaining to alternative measures of behavioral flexibility, however we include below only those that ended up being relevant. See the preregistration for the full list and the criteria that determined which variables to use (Supplementary Material 3). This article also attempt to test a Hypothesis 2 and its associated predictions, which are reported in Supplementary Material 2. The prediction numbers listed here maintain the original order from the preregistration to help readers track consistency across Stage 1 and Stage 2.*
**Hypothesis 1:** Behavioral flexibility is correlated with the exploration of new environments and novel objects, but not with boldness, persistence, or motor diversity.
**Predictions 1-5:** Behaviorally flexible individuals will be more exploratory of novel environments (P1) and novel objects (P2) than less flexible individuals, but there will be no difference in persistence (P3), boldness (P4), or motor diversity (P5) [as found in @logan2016behavioral].
**P1 alternative 4:** There is no correlation between exploration and behavioral flexibility because our novel object and novel environment methods are inappropriate for measuring exploratory tendency. These measures of exploration both incorporate novelty and thus may measure boldness rather than exploration. This will be supported by a positive correlation between behavioral responses to our exploration and boldness assays.
**P3 alternative 1:** There is a positive correlation between persistence and the number of incorrect choices in reversal learning before making the first correct choice. This indicates that individuals that are persistent in one context are also persistent in another context.
**P3 alternative 2:** There is no correlation between persistence and the number of incorrect choices in reversal learning before making the first correct choice. This indicates that flexibility is an independent trait.
## Methods {-}
### Preregistration details
The hypotheses, methods, and analysis plan are described in detail in the peer-reviewed preregistration, in Supplementary Material 3. We summarize these methods here, with any changes from the preregistration noted in the *Changes after the study began* section. The preregistration was written and submitted to Peer Community In (PCI) Ecology for peer review (Sep 2018) before collecting any data. After data collection began (and before any data analysis was conducted), we received peer reviews from PCI Ecology, revised, and resubmitted the preregistration (Feb 2019). It received an in principle recommendation in Mar 2019.
### Subjects
Grackles were caught in the wild in Tempe, Arizona USA using mist nets, walk-in traps and bow nets. Trapping could occur at any time of day when grackles were active. While some trapping methods can select for subjects with certain traits (e.g., boldness: @biro2009sampling; but see @brehm2018mind), mist nets are not visible to birds and no habituation is required, decreasing the probability of a selection bias for individuals that are more bold, food motivated, etc. Grackles were then individually housed in an aviary (each 244 cm long by 122 cm wide by 213 cm tall) where they had *ad lib* access to water. We aimed for a balanced sample of adult males and females, but because grackles in this population were difficult to catch, we ultimately ended up with only 4 females (15 males) and 2 juveniles (17 adults). Grackles were held in captivity until they completed the test battery, or 6 months had passed. All grackles were then released back into the wild and subsequently observed exhibiting normal behavior.
### Test battery
During testing (except exploration, see below) we food deprived grackles for up to four hours per day, but they had the opportunity to receive high value food items by participating in the assays. They had access to a maintenance diet at all other times. Individuals were given three to four days to habituate to the aviaries before their test battery began. Birds were then tested 6 days per week. On each testing day, we conducted multiple testing sessions where the duration of the session depended on the grackle’s motivation to participate or the task design (see below).
We use data from a recent investigation [@logan2023flexmanippcj; @lukas2024flexmanip] on the flexibility of 19 grackles, and here we additionally measured exploration and boldness in these same individuals. We also measured persistence and motor diversity through performance on two multiaccess boxes (MABs) in 17 of these grackles. The research described here is part of a larger project where the main goal was to better understand the impact of flexibility on diverse cognitive, behavioral, and physiological traits. Consequently, for all grackles we first assayed flexibility and implemented a flexibility training where half of the grackles underwent serial reversal learning and the other half received only one reversal and then control trials, described below. The training resulted in grackles more quickly changing their behavior when reward contingencies changed, relative to control grackles [@logan2023flexmanippcj]. By experimentally increasing the difference in behavioral flexibility between control and trained grackles, we increased our power to detect relationships between flexibility and other traits. After grackles passed the flexibility training, they received the subsequent behavioral trait assays in a randomized order. Grackles were assayed twice for exploration and boldness, and given sessions with the MABs until they passed criterion. Because there were two MABs, we also have two measures of persistence and motor diversity for each individual.
### Behavioral flexibility
We used the reversal learning paradigm to measure flexibility as the ability to change behavior when circumstances change. In the first phase of reversal learning, subjects learn an initial association between a stimulus (here, color) and food. The reversal phase then occurs where the food is switched to the other color and the measure of flexibility is how quickly the subject learns the new food-color association. The methods for the initial association and the reversal trials are identical, where, on each trial, grackles could choose to look inside one of two colored containers for food (Fig. 1a). After they make a choice, the experimenter removes both containers, refills the food if necessary, then replaces the containers for the next trial. The side that the rewarded container was on was pseudorandomized to never be on the same side more than twice in a row to inhibit grackles from forming a side bias. When grackles showed a significant preference for the rewarded color in the initial association phase, demonstrated by choosing correctly on 17 out of the most recent 20 trials, we switched the location of the food to the other colored container (a “reversal”). We measured baseline flexibility as the number of trials it took grackles to choose correctly on 17 out of the most recent 20 trials in this first reversal to demonstrate a change in preference to the second colored container. The flexibility training consisted of a randomized subset of grackles (n = 8) that received serial reversals where we switched the location of the food in multiple reversals after the grackle passed criterion in each reversal. Serial reversals continued until grackles were switching their preference in each reversal quickly enough to meet our experiment's passing criterion of two consecutive reversals in 50 trials or fewer. We chose a criterion of 50 trials based on an earlier study of grackle reversal learning performance [@logan2016behavioral] where 50 represented an approximately 30% increase in the speed that grackles switched their preference in the first reversal [@logan2023flexmanippcj]. Grackles needed 6-8 reversals to pass this serial reversal training. Instead of serial reversals, control grackles (n = 11) received equal testing experience with two identically colored containers, both containing a food item.
From the performance of each individual on reversal learning, we used Bayesian reinforcement learning models to create the Flexibility Comprehensive variables by modeling all of the choices that individuals made during the serial reversal learning experiment, and the uncertainty around these choices. Because we include the sequence of all correct and incorrect choices individuals made during reversal learning, these variables more effectively represent flexibility compared to more commonly used variables such as the number of trials to reverse a preference. The details of this model and the validation of it as a measure of flexibility are described elsewhere [@lukas2024flexmanip; @blaisdell2021more]. The Flexibility Comprehensive variables consist of two components: $\phi$ (the Greek letter phi) as the rate of learning to be attracted to a color option and $\lambda$ (the Greek letter lambda) as the rate of deviating from learned attractions that were previously rewarded. Thus, our two measures of flexibility, that we subsequently included as covariates explaining behavioral trait performance, were the Flexibility Comprehensive continuous variables or the dichotomous variable describing whether the grackle was in the flexibility trained or control group. There was one measure per individual for each of these variables.
All measures of the behavioral traits exploration, boldness, motor diversity, and persistence were collected after the serial reversal learning training was complete. By experimentally increasing the difference in flexibility performance between the trained and control grackles we increased our ability to detect a relationship, if it exists, between this trait and the other traits under investigation in this study.
### Behavioral traits
#### Boldness
We define boldness as an individual’s response to a potential threat [@reale2007integrating]. We measured boldness with two different threatening objects, a known threat (taxidermied Cooper’s hawk) and a novel threat (purple cat halloween decoration). We also included a known non-threat (taxidermied pigeon) as a control condition (Fig. 1d). Each individual was assayed with all three objects, presented in randomized order, across three days. Exposure to each object was limited to 15 minute trials, and a food item was placed next to the object. Boldness assays occurred while the grackle was food deprived to elicit approach behaviors. We conducted each of these assays twice to measure the repeatability of performance on this task to verify that the experimental designs elicited behaviors indicative of an inherent personality trait (as opposed to a passing motivational state). During boldness trials we measured multiple behaviors and, as preregistered, statistically analyzed the variable for which we ultimately had the most data, “Duration on the Ground”, encompassing the total time grackles spent within 100cm of the object.
#### Exploration
We defined exploration as an individual’s response to novelty [@reale2007integrating] to gather information that does not satisfy immediate needs [@mettke2002significance]. We used two different assays to measure exploratory tendency: novel environment (a small tent) and novel object (a pink fuzzy shape) exploration (Fig. 1b & 1c). We also conducted control conditions where we measured the grackle’s behavior in its familiar environment (the aviary) and with a familiar object (an empty water dish). Exploration tests occurred when the grackle was not food deprived to ensure that any approach to the novel object was for information gathering rather than food. Each trial was 45 minutes long and we always conducted the familiar condition trial immediately before the novel condition trial. We also conducted each of these assays twice to measure repeatability. As in boldness trials, we measured multiple behaviors during exploration trials and statistically analyzed the variable for which we ultimately had the most data. In the exploration of the novel environment condition we had the most data for two variables, “Duration near” (within 20cm) and “Latency to first land on the ground” within 100cm of the object, so we conducted one model for each variable. For the exploration of the novel object condition, we had the most data for “Latency to first land on the ground”.
#### Motor diversity and persistence
We defined motor diversity as the number of different motor actions used to solve novel problems on either of two multiaccess boxes (MABs; Fig. 1e & 1f). We used an ethogram (Table 1) to define and distinguish each interaction with the MABs. For each grackle, we summed the number of distinct motor actions they used while interacting with each MAB, resulting in two values for each grackle. We quantified persistence as the number of touches to a novel apparatus per trial time [@logan2016behavioral; @griffin2015innovative], where the novel apparatuses included the novel environment and novel object from the exploration assays, the potentially threatening boldness objects, as well as the two MABs. We summed the number of touches grackles made to each apparatus, resulting in a value of persistence for each test apparatus, if the grackle received that test (e.g., two grackles did not participate in the MAB tests). We further distinguished touches to the MABs based on whether they were functional (touches to the doors or loci that could result in getting the food item) or nonfunctional (touches to the side of the box that would never result in food). Motor diversity and persistence were coded from videos of grackles interacting with the two different MAB apparatuses for a separate experiment on problem solving ability [@logan2023flexmanippcj], as well as the novel apparatuses from the exploration and boldness assays.
### Statistical analyses
*General analysis plan* - For all analyses, we used the MCMCglmm function in the MCMCglmm R package [@hadfield2010mcmc]. Our preregistered analysis plan was to use a Poisson distribution and log link for both the repeatability analyses and analyses testing the correlation of behavioral traits with flexibility. However, we used the DHARMa package [@hartig2019dharma] to verify that the data for each analysis met the assumptions for Poisson regression and modified the model family accordingly (see below in *Changes after the study began*). We started each model with 13,000 iterations, a thinning interval of 10, a burnin of 3,000, and minimal priors (V=1, nu=0). We checked that the GLMM showed acceptable convergence [i.e., lag time autocorrelation values <0.01 @hadfield2010mcmc], and adjusted the number of iterations, thinning and burnin if necessary. Due to our unbalanced sample of sex and age we checked whether these variables significantly impacted the response. We found that these covariates did not have a significant effect on any of the models (described below), so we omitted them from the final models (see Changes after the study began section).
*Repeatability* - We obtained repeatability estimates that account for the observed and latent scales. The repeatability estimate indicates how much of the total variance, after accounting for fixed and random effects, is explained by individual differences. For each behavioral trait, we included fixed effects to control for variation in the response not attributable to individual differences and consequently we report the adjusted repeatability estimates. All models included a covariate describing whether the grackle was flexibility trained or in the control group. Our boldness model additionally included a covariate for threat condition (hawk or cat). For persistence, we additionally included a covariate for assay type and one for the total time the grackle had access to an assay to control for opportunity to make functional or non-functional touches. The motor diversity model included an additional covariate for assay type. Marginal and conditional R-squared values are reported in Table S1 of Supplementary Material 2 to illustrate the impact of fixed effects on repeatability estimates.
From the posterior distribution of the MCMCglmm model for each behavioral trait, we extracted the Bird ID random effect variance to calculate the ratio of variance accounted for by individual differences relative to total variance [@nakagawa2010repeatability]. We used the mean value of this ratio across all iterations for a given behavioral trait as our measure of repeatability. We used the HPDinterval function from the coda package [@plummer2020coda] to calculate credible intervals around our repeatability estimate. We used permutation tests that randomized data among individuals to test the significance of the repeatability value.
*Relationship with flexibility* - If performance was repeatable across two time points in the behavioral trait assays, we used the average value per bird per assay in Bayesian multivariate models to investigate whether performance was related to the Flexibility Comprehensive variables ($\phi$ and $\lambda$). As such, the performance variables from each behavioral trait assay were the dependent variables and $\phi$ and $\lambda$ were the independent variables. We assessed the relationship between flexibility and the behavioral trait by interpreting the parameter estimates from these models. Similarly, we used Bayesian bivariate models to analyze whether there was a difference in performance on the behavioral trait assays between grackles that underwent serial reversal learning flexibility training relative to grackles in the control group.
{width=45%}
Figure 1: This experiment assessed the relationship between multiple different behavioral tests and contexts. We quantified and increased behavioral flexibility with serial reversal learning of a color preference: a light gray and a dark gray tube (a), we determined individual differences in exploration of a novel environment: a tent (b), exploration of a novel object: a homemade pink fuzzy shape (c), boldness towards threatening objects (purple halloween cat and Cooper’s hawk) compared to a known non-threat (pigeon) (d), we cataloged motor diversity when interacting with novel foraging problems on the two multiaccess boxes (e-f), and we measured persistence by counting the number of touches to all novel apparatuses (b, c, d, e, and f).
\newpage
Table 1. Motor action ethogram for the two multiaccess box experiments. Any of the four modifiers can be added to any of the six motor actions. However, Stand only goes with the On top modifier, resulting in a total of 21 unique motor actions. For example, Vertical Peck is a peck to a vertical surface, and Gape Upside Down is a gape with the head being held upside down. Note that one interaction can be coded in multiple categories (e.g., if a bird pulls the string first horizontally and then vertically).
{width=60%}
## Changes after the study began
**After data collection began and before data analysis:**
1) We added an *unregistered analysis* to assess interobserver reliability for the response variables to determine how repeatable our data collection was by having the videos coded by multiple coders. This unregistered analysis is described, and results reported, in the Supplementary Material 1.
**After data collection and during data analysis:**
1) We conducted an *unregistered analysis* to compare the grackles’ responses to the familiar item with responses to the novel/threatening items in the exploration and boldness assays. The definition for boldness relates to the behavioral response to threat, so we would expect a decrease in interactions with the novel/threatening items relative to the control item. To test that this occurred, and the grackles perceived the items as threatening, we used MCMCglmm to model the effect of condition (novel or familiar item trial) on the latency to approach and the duration spent in proximity to the items in the exploration assays. We used a gaussian distribution for latency to approach and Poisson distribution for the duration spent in proximity. We included a covariate that identified whether the bird was in the flexibility trained (or control group) and a random effect for bird ID. The boldness data were overdispersed and zero-inflated so we used a zero-inflated negative binomial mixed model with the R package NBZIMM [@zhang2020nbzimm]. In this model, we also included a covariate for the flexibility trained group and a random effect for bird ID.
2) For the repeatability analyses, we preregistered that we would calculate repeatability from the ratio of variance components extracted from MCMCglmm models. We also obtained credible intervals from the posterior distribution of these models. However, repeatability is a ratio so values can never be less than zero. As such, we are not able to ascertain the significance of our repeatability values by determining whether the credible interval overlaps with zero. We conducted an *unregistered analysis* to obtain p-values indicating whether performance was significantly more repeatable than random by utilizing the built in permutation tests in the rptR package [@stoffel2017rptr]. This also ensured that repeatability values and credible intervals were consistent with the preregistered MCMCglmm methods to validate that our non-informative priors were appropriate.
3) The boldness data were zero-inflated (69% of the data were zeros) and overdispersed, such that the appropriate model for this kind of count data is a zero-inflated negative binomial model. As stated above, we used this model type in the *unregistered analysis* to compare the responses between the threatening and non-threatening contexts. To assess repeatability of performance on the boldness assays, we preregistered that we would use a MCMCglmm model with a Poisson distribution. The boldness data were not appropriate for Poisson and we do not know of a method for obtaining the variance components for the repeatability calculation from a zero-inflated negative binomial model. Consequently, for the repeatability analysis we used a logistic regression, where the response was 0 (the grackle never approached the object during boldness trials) or 1 (the grackle approached the object during boldness trials).
4) For repeatability analyses of the exploration and persistence data, we originally planned to conduct a model with a Poisson distribution. However, the data checking process detected significant zero-inflation and heteroscedasticity in the Poisson models. We log-transformed the latency to approach (for exploration) and number of touches (for persistence) for the gaussian model, which was normally distributed and not heteroscedastic, therefore we used a gaussian distribution instead.
5) When we originally submitted this preregistration, we anticipated measuring motor diversity on only one multiaccess box (MAB). However, as part of a different experiment within our overall project, we added a second, but distinct MAB. Consequently, we did not preregister a repeatability analysis for motor diversity because there would have been only one measure per bird. We added an *unregistered analysis* to assess motor diversity repeatability. We used a Poisson regression and included a covariate for whether the grackle was flexibility trained or not. We also included an offset for the total trial time with the MABs to control for variation in the opportunity to express motor behaviors.
6) During the exploration environment assays, very few grackles stepped inside the tent (n = 4), so we did not have enough data to use the following preregistered variables in the analysis relating exploration and behavioral flexibility: Latency to enter a novel environment inside a familiar environment, Time spent in each of the different sections inside a novel environment or the corresponding areas on the floor when the novel environment is not present (familiar environment) as an interaction with the Environment Condition: activity in novel environment vs. activity in familiar environment, Time spent per section of a novel environment or in the corresponding areas on the floor when the novel environment is not present (familiar environment) as an interaction with the Environment Condition: time spent in novel environment vs. time spent in familiar environment.
7) We also realized that, because we experimentally increased reversal learning speed through serial reversal learning [@logan2023flexmanippcj], behavioral flexibility should be the independent rather than dependent variable.
8) We found [@blaisdell2021more; @lukas2024flexmanip] that the "Flexibility Comprehensive" variables were much more effective at representing flexibility than the other variables we preregistered (e.g., Trials to reverse in the last reversal). Additionally, we found that solution switching on the MAB is correlated with reversal performance and including this as an additional variable describing flexibility will not significantly add to the variance explained. Because the individual’s serial reversal learning training condition (control or trained) is accounted for in the Flexibility Comprehensive variable, we did not include condition as an additional independent variable in these models. Note that we still conducted the preregistered analyses testing the relationship between performance on the behavioral trait assays and whether the individual was in the control or flexibility trained group.
9) We preregistered that we would include “Age” as a covariate in our models relating performance on the behavioral trait assays to flexibility if we tested juveniles as well as adults, though our plan was to only test adults. Our sample ultimately included two juveniles because the grackles were more difficult to catch than expected and we struggled to meet our minimum sample size. Similarly, it is possible that Sex could influence performance, but we only tested 4 females because they were more difficult to trap than males. We did not find that including a covariate for Age and Sex changed any of our results (repeatability or relationship with flexibility). Therefore, to maintain greater statistical power, we decided not to include Age or Sex as covariates in the final models.
10) We added an additional persistence repeatability analysis to test whether nonfunctional touches were consistent across the two different MABs. We preregistered that we would separately evaluate the relationship between flexibility and functional or nonfunctional touches, but, because flexibility was originally the dependent variable, we did not preregister this repeatability analysis.
11) We made two modifications to the analysis testing the relationship between persistence and flexibility. We preregistered that we would use all of the data, including the repeated measures, with a random effect for individual ID in a Poisson model. However, the full data set was zero-inflated. Because persistence was repeatable across assays, we took the average for each individual to use as the dependent variables in our models. Consequently, there was no potential for within-individual clustering in the data and we did not include the random effect for individual ID. Secondly, we were interested in the number of touches to novel objects per time. As such, we used a Poisson model as preregistered, but with an added offset term for trial time.
12) We preregistered that we would compare performance on the boldness and exploration assays between grackles in the aviaries and those tested in the wild. However, we were unable to collect a large enough sample size to quantitatively test this hypothesis, therefore we present what we have in Supplementary Material 2.
# RESULTS {-}
## Repeatability
Our first goal was to assess the repeatability of grackle boldness, exploration, persistence and motor diversity behaviors across time and different contexts. We collected boldness and exploration data on 19 individuals, but 2 of these individuals did not participate in the MAB tasks and so our sample size was 17 for the repeatability of persistence and motor diversity.
### Boldness
We first conducted an *unregistered analysis* to evaluate whether grackles perceived the objects presented to them during boldness trials as threatening. Relative to the pigeon control condition (the known non-threat), we found that grackles spent 55% less time on the ground within 100cm of the cat (*p* = 0.00) and 61% less time on the ground in the presence of the hawk (*p* = 0.00). There was a nonsignificant 9.5% decrease in duration on the ground in the hawk condition relative to the cat condition (*p* = 0.71). Consequently, there is evidence that the grackles perceived the cat and hawk as more threatening than the pigeon, and we only use data from the cat and hawk assays in all subsequent analyses including boldness. Despite the perceived threat, 12 out of 19 grackles spent time on the ground in the presence of the hawk and 7 out of 19 grackles spent time on the ground with the cat at some point during the 15-minute boldness trials.
Next, we assessed whether grackles reacted consistently towards each threatening object across two time periods (temporal repeatability). Because the repeatability analysis was not possible with a zero-inflated negative binomial model, we instead used a binomial model where our dependent variable represented whether the duration grackles spent within 100cm of the threatening object was greater than 0 seconds (1) or not (0). We found no evidence for repeatability of performance in either the cat (*Repeatability* = 0.18, CI = 0.00-0.96, *p* = 0.22) or hawk (*R* = 0.00, CI = 0.00-0.44, *p* = 0.48) assays (Fig. 2). Similarly, when we considered grackle performance across the two different threatening contexts (contextual repeatability) there was also no consistency in behavioral response (*R* = 0.04, CI = 0.00-0.28, *p* = 0.22).
It is possible that the lack of repeatability is because habituation to the potentially threatening object occurs after the first exposure [@greggor2015neophobia; @takola2021novelty]. We conducted an *unregistered analysis* and found that grackles did spend significantly longer on the ground during the second cat, hawk and novel object (which the grackles considered threatening, see below) trials, relative to the first trials (Poisson model: *ß* = 0.85, p < 0.01). To check whether this explains the lack of contextual repeatability in this behavioral trait, we conducted a second *unregistered analysis* evaluating repeatability of performance in only the first trial in response to the potentially threatening contexts. We still found no evidence that response to the potentially threatening objects was repeatable across these contexts (*R* = 0.00, CI = 0.00-0.17, *p* = 1; Fig. S3).
```{r POSTrepeatableBold, eval=FALSE, message=FALSE, warning=FALSE, include=FALSE, results='asis'}
#Boldness
bol <- read.csv("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_exploration_data_boldness.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE)
bol = bol[which(bol$IndicatedTrial == 2 & bol$AviaryOrWild == "Aviary"),-c(1:5,22:25)]
## Most data in Duration on floor - 15 out of 19 grackles came to the ground during at least 1 condition
head(bol) #Check to make sure it looks right
# add column identifying whether bird was in the flexibility manipulation or control groups
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d$ID <- as.factor(d$ID)
#remove pilot birds
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",]
#extract just bird name and flex group
flexID = unique(d[,c(4,5)])
colnames(flexID) = c("Name","FlexGroup")
#Taco did initial discrimination and 1 reversal, so he is considered Control group for this analysis
flexID$FlexGroup[which(flexID$Name == "Taco")]<- "Control"
# Add band ID bird names to data frame to merge it with boldness data
biometrics = read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Data/data_biometricsAZ.csv"), header=T, sep=",", stringsAsFactors=F)
biometrics = unique(biometrics[,c(1,2,13,14)]) # add sex and age per post-study Reviewer comment 34 & 36
flexID = merge(flexID, biometrics, by = "Name")
# Fix BirdIDs entered incorrectly in boldness data sheet
bol$BirdID[which(bol$BirdID == "A035P")] <- "A035P-"
bol$BirdID[which(bol$BirdID == "A036R")] <- "A036R-"
bol$BirdID[which(bol$BirdID == "A075Y")] <- "A075Y-"
bol = merge(bol, flexID, by = "BirdID", all = T)
# remove NA birds that were in the aviaries but did not complete boldness assays (4 birds)
bol = bol[-which(is.na(bol$Condition)),]
### total duration on ground: duration near + duration far
# Significantly correlated with Latency to land on ground (r = -0.82, p << 0.01)
bol$TotalDurationNear.20cm = as.numeric(bol$TotalDurationNear.20cm)
bol$TotalDurationNear.20cm[which(is.na(bol$TotalDurationNear.20cm))]<-0
bol$TotalDurationFar.20cm = as.numeric(bol$TotalDurationFar.20cm)
bol$TotalDurationFar.20cm[which(is.na(bol$TotalDurationFar.20cm))]<-0
bol$DurationOnGround = bol$TotalDurationFar.20cm + bol$TotalDurationNear.20cm # duration on ground means within 1m of object
####### FIGURING OUT DATA STRUCTURE FOR REPEATABILITY ANALYSIS ######
hist(bol$DurationOnGround) #definitely looks zero-inflated
library(lme4)
d1 = glmer.nb(round(DurationOnGround) ~ Condition + FlexGroup + Age + Sex + (1|BirdID), data = bol)
d2 = glmer(round(DurationOnGround) ~ Condition + FlexGroup + Age + Sex + (1|BirdID),data = bol, family = poisson)
# function from Ben Bolker for calculating overdispersion in glmm
overdisp_fun <- function(model) {
rdf <- df.residual(model)
rp <- residuals(model,type="pearson")
Pearson.chisq <- sum(rp^2)
prat <- Pearson.chisq/rdf
pval <- pchisq(Pearson.chisq, df=rdf, lower.tail=FALSE)
c(chisq=Pearson.chisq,ratio=prat,rdf=rdf,p=pval)
}
overdisp_fun(d1) # both overdispersed, use zero-inflated negative binomial model
#### UNREGISTERED ANALYSIS: Is response different to cat and hawk vs pigeon? ####
# C1 = cat, C2 = pigeon, C3 = hawk
library(remotes)
install_github("nyiuab/NBZIMM", force=T, build_vignettes=F)
library(NBZIMM)
# C3 is NOT different from C1 (ß = -0.14, p = 0.52) - no difference in time on the ground between the cat and the hawk
d3 = glmm.zinb(DurationOnGround ~ Condition + FlexGroup + Age + Sex + offset(log(TrialDuration)), random = ~1|BirdID, data = bol)
summary(d3) # Output displayed below chunk
# reorder factor levels to get difference between C2 & C3
bol$Condition = factor(bol$Condition, levels=c('C2', 'C3', 'C1'))
d3 = glmm.zinb(DurationOnGround ~ Condition + FlexGroup + Age + Sex + offset(log(TrialDuration)), random = ~1|BirdID, data = bol)
summary(d3)
# response to C2 is different from C1 (ß = -0.80, p = 0) & C3 (ß = -0.95, p = 0) - significantly less time on the ground with the cat and hawk than the pigeon
# The cat and hawk did not result in different time on the ground (ß = -0.1, p = 0.71)
#exponentiate the coefficient to get the rate of change in Duration on ground.
### So, our control condition (known non-threat) worked and C1 & C3 seem to be perceived as threatening. Now only model repeatability of the response to threatening objects (C1 & C3) ###
hist(bol$DurationOnGround[-which(bol$Condition == "C2")])
d1 = glmer.nb(round(DurationOnGround) ~ FlexGroup + Age + Sex + (1|BirdID), data = bol[-which(bol$Condition == "C2"),])
d2 = glmer(round(DurationOnGround) ~ FlexGroup + Age + Sex + (1|BirdID),data = bol[-which(bol$Condition == "C2"),], family = poisson)
overdisp_fun(d2) # both overdispersed, use zero-inflated negative binomial model
d3 = glmm.zinb(fixed = round(DurationOnGround) ~ FlexGroup + Age + Sex, random = ~1|BirdID, data = bol[-which(bol$Condition == "C2"),])
summary(d3)
# No effect of FlexGroup on response to threatening objects
# but cannot get variance components for repeatability calculation from zinb model?
### For repeatability, need to binarize performance to 0 (did not come down) and 1 (came to the ground)
bol$binDur = ifelse(bol$DurationOnGround >0, 1, 0)
bol$Condition <- factor(bol$Condition, labels = c("Pigeon","Hawk","Cat"))
library(rptR)
rptC1 = rpt(binDur ~ FlexGroup + (1|BirdID), grname = "BirdID", data = bol[which(bol$Condition == "Cat"),], datatype = "Binary", nboot = 1000, npermut = 200)
# R = 0.18, p = 0.215, CI = 0-0.96
rptC1.base = rpt(binDur ~ (1|BirdID), grname = "BirdID", data = bol[which(bol$Condition == "Cat"),], datatype = "Binary", nboot = 1000, npermut = 200)
# R = 0.25, p = 0.155, CI = 0-0.97
summary(glmer(binDur ~ FlexGroup + (1|BirdID), data = bol[which(bol$Condition == "Cat"),], family = binomial(link = "logit")))
### Reviewer comment 5: Covariate FlexGroup is not accounting for a significant amount of variance.
### Reviewer comment 34 & 36: 4 females (all adults) & 2 juveniles (both male), rpt models won't run with Sex and Age covariates because of unbalanced sample. Remove females and juveniles to see if results are different
bol.red = bol[-which(bol$Sex == "F" | bol$Age == "J"),]
rptC1.red = rpt(binDur ~ FlexGroup + (1|BirdID), grname = "BirdID", data = bol.red[which(bol.red$Condition == "Cat"),], datatype = "Binary", nboot = 1000, npermut = 200)
# R = 0.01, p = 0.37 - Repeatability is even lower and still not significantly different from random
rptC3 = rpt(binDur ~ FlexGroup + (1|BirdID), grname = "BirdID", data = bol[which(bol$Condition == "Hawk"),], datatype = "Binary", nboot = 1000, npermut = 200)
# R = 0, p = 0.48
rptC3.base = rpt(binDur ~ (1|BirdID), grname = "BirdID", data = bol[which(bol$Condition == "Hawk"),], datatype = "Binary", nboot = 1000, npermut = 200)
summary(glmer(binDur ~ FlexGroup + (1|BirdID), data = bol[which(bol$Condition == "Hawk"),], family = binomial(link = "logit")))
### Reviewer comment 5: Covariate FlexGroup is not accounting for a significant amount of variance.
### Reviewer comment 34 & 36 - Juveniles and females removed:
rptC3.red = rpt(binDur ~ FlexGroup + (1|BirdID), grname = "BirdID", data = bol.red[which(bol.red$Condition == "Hawk"),], datatype = "Binary", nboot = 1000, npermut = 200) ### Will not run. Trying likelihood ratio test:
b1 = glmer(binDur ~ FlexGroup + (1|BirdID), data = bol[which(bol$Condition == "Hawk"),], family = binomial(link = "logit"))
b2 = glm(binDur ~ FlexGroup, data = bol[which(bol$Condition == "Hawk"),], family = binomial(link = "logit"))
anova(b1,b2) # Not repeatable still with juvies and females removed.
## Boldness is NOT repeatable ##
# easier to see individual inconsistency with DurationOnGround than the 0/1 variable we used in the analysis where the lines lie on top of each other
library(ggplot2)
bol$FlexGroup=factor(bol$FlexGroup, levels = c("Control","Manipulation"), labels = c("Control","Trained"))
ggplot(bol[-which(bol$Condition == "Pigeon"),]) +
geom_line(aes(x = as.factor(Time), y = DurationOnGround, group = BirdID, color = BirdID),
size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = DurationOnGround, color = BirdID, shape = FlexGroup,
size = 0.7, alpha = 0.7)) +
facet_grid(.~Condition) +
labs(x = "Time", y = "Duration (sec) within 100cm") +
theme_bw() +
theme(axis.text = element_text(size = 14),
axis.title = element_text(size = 20),
plot.title = element_text(size = 26),
strip.text.x = element_text(size = 20)) +
theme(legend.title = element_text(size=16),
legend.text = element_text(size=14)) +
ggtitle("Boldness") +
guides(color = FALSE,
shape=guide_legend(title="Serial reversal \n learning group", override.aes = list(size = 5))) +
guides(alpha = F) + guides(size = F)
############ Registered Analysis: Now double-check repeatability in MCMCglmm #############
## DATA CHECKING FOR MCMC GLMM
library(DHARMa)
library(lme4)
simulationOutput <- simulateResiduals(fittedModel = glmer(bol$binDur ~ FlexGroup + (1|bol$BirdID), family=binomial, data=bol[-which(bol$Condition == "Pigeon")], na.action = na.omit), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutput$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
# flat distribution
testDispersion(simulationOutput) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation
# p > 0.05 so NOT over/under-dispersed
testZeroInflation(simulationOutput) #compare expected vs observed zeros, not zero-inflated if p>0.05
# p > 0.05 so NOT zero inflated
testUniformity(simulationOutput) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p=0.05.
# p > 0.05 so NOT heteroscedastic
plot(simulationOutput) #...there should be no pattern in the data points in the right panel
#plotResiduals(bol$LatencyFirstTouchToFood, simulationOutput$scaledResiduals) #plot the residuals against other predictors (in cases when there is more than 1 fixed effect) - can't get this code to work yet
library(MCMCglmm)
prior = list(B=list(mu=c(0,0,0), V=gelman.prior(~FlexGroup+Condition,
data=bol[-which(bol$Condition == "Pigeon"),],scale=sqrt(pi^2/3+1))),
G=list(G1=list(V=1,nu=1,alpha.mu=0,alpha.V=1000)),
R=list(V=1,fix=1))
bold <- MCMCglmm(binDur ~ FlexGroup + Condition, random=~BirdID, family="categorical", data=bol[-which(bol$Condition == "Pigeon"),], verbose=F, prior=prior, nitt=6300000, thin=1000, burnin=5000)
summary(bold)
autocorr(bold$Sol) #Did fixed effects converge? (<0.1)? yes, after increasing iterations
autocorr(bold$VCV) #Did random effects converge? (<0.1)? yes
#Advice from Maxime Dahirel in the review for flexmanip on how to calculate repeatability from MCMCglmm (https://ecology.peercommunityin.org/public/rec?id=17&reviews=True). Dahirel says: “7- In P3a, you use a linear mixed model (lmer) to estimate repeatability when a generalized linear mixed model (glmer) should be used, as the dependent variable is a count. This would lead to potentially wrong estimates of repeatability, first because the individual variance will probably be wrongly estimated, and then because the residual/overdispersion variance is not the same for a Gaussian vs a Poisson model (Nakagawa & Schielzeth, 2010). If you want to extract correct repeatabilities from a lme4 (G)LMM (and their 95% CI) on both the response and latent scales, you can use the rptR package (Stoffel, Nakagawa, & Schielzeth, 2017). However, since you plan to fit your GLMM using MCMCglmm you actually don’t need that at all, since the latent scale adjusted repeatability and its credible interval can simply be obtained by mod$VCV[,ID]/(mod$VCV[,ID]+mod$VCV[,units]+mod$VCV[,any other included random effect]). For the raw repeatability, simply fit a model with no covariates. For the repeatability on the response scale, see (P. de Villemereuil, Morrissey, Nakagawa, & Schielzeth, 2018; Pierre de Villemereuil, Schielzeth, Nakagawa, & Morrissey, 2016) and the QGglmm R package.”
#Therefore, because MCMCglmm can easily calculate repeatability on the latent scale, there is no need to transform this back to the observed scale.
repeata <- bold$VCV[,"BirdID"]/(bold$VCV[,"BirdID"]+bold$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeata) # 0.02
var(repeata) # 0.08
posterior.mode(repeata) # << -0.01
HPDinterval(repeata, 0.95) # 0 - 0.11
# R = 0.02 (CI: 0, 0.10)
# Addressing Reviewer 5 comment:
bol.base <- MCMCglmm(binDur ~ 1, random=~BirdID, family="categorical", data=bol[-which(bol$Condition == "Pigeon"),], verbose=F, prior=prior, nitt=6000000, thin=1000, burnin=5000)
repeat.base <- bol.base$VCV[,"BirdID"]/(bol.base$VCV[,"BirdID"]+bol.base$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeat.base) # 0.01
# from Nakagawa & Schielzeth 2013
c2 <- (16 * sqrt(3)/(15 * pi))^2
bold$Sol1 <- bold$Sol/sqrt(1+c2 * bold$VCV[, "units"])
bold$VCV1 <- bold$VCV/(1+c2 * bold$VCV[, "units"])
mFixed <- mean(bold$Sol1[,2]) * bold$X[, 2] + mean(bold$Sol1[, 3]) * bold$X[, 3]
mVarF <- var(as.vector(apply(bold$Sol,2,mean) %*% t(bold$X)))
mVarF/(mVarF+sum(apply(bold$VCV1,2,mean)))
# alternative with credible intervals
vmVarF<-numeric(1000)
for(i in 1:1000){
Var<-var(as.vector(bold$Sol1[i,] %*% t(bold$X)))
vmVarF[i]<-Var}
(mVarF)/(mVarF + sum(apply(bold$VCV1,2,mean)[-3])+pi^2/3)
R2m<-vmVarF/(vmVarF+bold$VCV1[,1]+bold$VCV1[,2]+pi^2/3)
mean(R2m) # R2 marginal = 0.07
posterior.mode(R2m)
HPDinterval(R2m) # 0 - 0.18
(mVarF+sum(apply(bold$VCV1,2,mean)[-3]))/(mVarF + sum(apply(bold$VCV1,2,mean)[-3])+pi^2/3)
R2c<-(vmVarF+bold$VCV1[,1]+bold$VCV1[,2])/(vmVarF+bold$VCV1[,1]+bold$VCV1[,2]+pi^2/3)
mean(R2c) # R2 conditional = 0.14
posterior.mode(R2c)
HPDinterval(R2c) # 0.19 - 0.61
# Reviewer comment 5: FlexGroup & Boldness condition covariates do account for a some variance.
```
{width=70%}
Figure 2: The grackles did not respond consistently to the threatening objects across the two time points. Each line color represents an individual and the points show the number of seconds individuals spent on the ground within 100cm of the threatening object during each of the two 15-minute trials (Time 1 and Time 2). The shape of the point is based on whether the grackle was part of the control (circle) or trained (triangle) group in the serial reversal learning experiment. The two time periods were separated by an average of 33 days (range: 11-49 days). If performance is repeatable we would expect the line connecting the two points to be at or close to horizontal, and the lines of different individuals to be approximately parallel.
```{r repeatableBol posthoc, eval=FALSE, warning=FALSE, include=FALSE, results='asis'}
#Add explore object data to boldness data because grackles perceived it as a potential threat
exp.o2 = exp.o[-which(exp.o$Condition == "Familiar"),-2] # exp.o is created below in Chunk 6
colnames(exp.o2)[2] = "Test"
exp.o2$Test = "Novel Object"
exp.o2 = exp.o2[,c(1:3,14:16)]
bol2 = bol[-which(bol$Condition == "Pigeon"),-c(2,3)]
colnames(bol2)[2] = "Test"
bol2 = bol2[,c(1:3,15:16,19)]
newBold = rbind(bol2, exp.o2)
# Reviewer comment 37
summary(glmer(round(DurationOnGround) ~ as.factor(Time) + FlexGroup + (1|BirdID), data = newBold, family = poisson)) # grackles spend more time on the ground in Time 2 relative to Time 1.
newBold2 = aggregate(DurationOnGround~Name + FlexGroup + Test, FUN = "mean", data = newBold) #average performance from time 1 & time 2
newBold = newBold[which(newBold$Time == 1),] #performance only from time 1
newBold$Test = as.factor(as.character(newBold$Test))
newBold2$olre = 1:nrow(newBold2)
library(DHARMa)
library(lme4)
simulationOutput <- simulateResiduals(fittedModel = glmer(round(DurationOnGround) ~ FlexGroup + (1|Name) + (1|olre),
family = "poisson", data=newBold2), n=250)
testDispersion(simulationOutput) # underdispersed
testZeroInflation(simulationOutput) # not zero inflated
testUniformity(simulationOutput) # slightly heteroscedastic
plot(simulationOutput$scaledResiduals)
plot(simulationOutput)
# Data are still a poor fit for Poisson (even with olre) or Gaussian. Again we will binarize the response as the bird came to the ground (1) or did not (0) in the presence of the threatening object
newBold$binDur = ifelse(newBold$DurationOnGround >0,1,0)
simulationOutput <- simulateResiduals(fittedModel = glmer(binDur ~ FlexGroup + (1|BirdID), family = binomial(link = "logit"),
data=newBold), n=250)
testDispersion(simulationOutput) # normally dispersed
testZeroInflation(simulationOutput) # not zero inflated
testUniformity(simulationOutput) # not heteroscedastic
plot(simulationOutput$scaledResiduals)
plot(simulationOutput)
newBolrpt = rpt(binDur ~ FlexGroup + (1|Name),grname="Name",datatype="Binary",link = "logit",
nboot = 200, npermut = 100, data = newBold)
newBolrpt # repeatability = 0
newBolrpt2 = rpt(round(DurationOnGround) ~ FlexGroup + (1|Name),grname = "Name",datatype = "Poisson",
nboot = 200, npermut = 100, data = newBold2)
newBolrpt2 # repeatability still close to 0
nb1 = glmer(round(DurationOnGround) ~ FlexGroup + (1|Name), family = poisson,data = newBold)
nb2 = glm(round(DurationOnGround) ~ FlexGroup, family = poisson, data = newBold)
nb3 = glmer(round(DurationOnGround) ~ FlexGroup + (1|Name) + (1|olre), family = poisson,data = newBold)
anova(nb1,nb3) # random effect of bird name does not significantly add to variance explained
library(ggplot2)
ggplot(newBold2) +
geom_line(aes(x = as.factor(Test), y = DurationOnGround, group = Name, color = Name), size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Test), y = DurationOnGround, color = Name, size = 0.7,alpha = 0.7)) +
labs(x = "Threatening object", y = "Duration (sec) within 100cm") +
theme_bw() +
theme(axis.text = element_text(size = 14),
axis.title = element_text(size = 20),
plot.title = element_text(size = 26),
strip.text.x = element_text(size = 20)) +
ggtitle("Boldness") +
theme(legend.position="none")
```
### Exploration
Similar to boldness, we assessed the repeatability of exploratory behavior across two time points and across two different contexts: a novel object and a novel environment. Because novel items might elicit a response based on the boldness personality trait rather than an exploratory response [our P1 alternative 4 described above; @carter2013animal], we also compared the novel environment and novel object responses to control conditions with a familiar environment and a familiar object to determine whether grackles perceived the novelty as threatening (this is an *unregistered analysis*). We found no difference in the latency of individuals to approach the novel compared to the familiar environment (*ß* = 0.29, CI = -0.24-0.81, *p* = 0.27), or the duration they spent near the novel and familiar environments (*ß* = -0.61, CI = -1.47-0.20, *p* = 0.14). In contrast, grackles took significantly longer to approach the novel object relative to the familiar object (*ß* = 2.11, CI = 1.22-2.89, *p* < 0.01), indicating the novel object may have been perceived as threatening.
We found that the latency to approach the novel environment across time points 1 and 2 was highly repeatable (*R* = 0.72, CI = 0.42-0.88, *p* < 0.01). Similarly, the duration spent near the novel environment was also highly repeatable (*R* = 0.85, CI = 0.67-0.98, *p* < 0.01). However, the latency to approach the novel object was not repeatable (*R* = 0.05, CI = 0-0.5, *p* = 1; Fig. 3). When we assessed performance across the novel environment and novel object tasks, we found that latency to approach was repeatable across the two different contexts, but this result was driven by the very high between-individual variance in the environment assay (*R* = 0.49, CI = 0.21-0.69, *p* = 0; Fig. S1).
```{r POSTrepeatableExpEnv, eval=FALSE, warning=FALSE, include=FALSE, results='asis'}
#Exploration of novel environment
ee <- read.csv("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_exploration_data_exploration.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE)
head(ee) #Check to make sure it looks right
#want only Test=Environment (not Object)
ee <- ee[ee$Test=="Environment",]
#changed LatencyFirstLand NAs to a number higher than the assay session length so they show up as data points? yes. Set latency for these at 3060 (51 minutes: the highest assay duration was 50 mins)
ee$LatencyFirstLand[which(is.na(ee$LatencyFirstLand))]<-3060
ee$LatencyFirstLand <- as.numeric(ee$LatencyFirstLand)
ee$TotalDurationNear.20cm <- as.numeric(ee$TotalDurationNear.20cm)
#LatencyFirstLand or Duration has the most data so will use one of these variables. Histograms for both look poisson
ee$BirdID <- as.factor(ee$BirdID)
# add column identifying whether bird was in the flexibility manipulation or control groups
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d$ID <- as.factor(d$ID)
#remove pilot birds
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",]
#extract just bird name and flex group
flexID = unique(d[,c(4,5)])
colnames(flexID) = c("Name","FlexGroup")
#Taco did initial discrimination and 1 reversal, so he is considered Control group for this analysis
flexID$FlexGroup[which(flexID$Name == "Taco")]<- "Control"
# Add band ID bird names to data frame to merge it with boldness data
biometrics = read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Data/data_biometricsAZ.csv"), header=T, sep=",", stringsAsFactors=F)
biometrics = unique(biometrics[,c(1,2,13,14)]) # add Age & Sex per Reviewer comments 34 & 36
flexID = merge(flexID, biometrics, by = "Name")
colnames(ee)[1] <- "Name"
exp = merge(ee, flexID, by = "Name", all = T)
# remove NA birds that were in the aviaries but did not complete exploration assays (4 birds)
exp = exp[-which(is.na(exp$Condition)),]
exp2 = exp[which(exp$Condition == "Novel"),]
##### SIDE NOTE (Oct 2026): Corina and Dieter added a useful boxplot for presentations showing that the manipulated grackles spent much more time near the tent than the control individuals
time1expl<-exp2[exp2$Time==1,]
time2expl<-exp2[exp2$Time==2,]
time1expl$standTotalDurationNear<-(time1expl$TotalDurationNear.20cm-mean(time1expl$TotalDurationNear.20cm))/sd(time1expl$TotalDurationNear.20cm) #Standardize so that Zero = average duration spent near tent, negative values = lower duration at times 1 and 2, and positive values = longer durations at times 1 and 2
time2expl$standTotalDurationNear<-(time2expl$TotalDurationNear.20cm-mean(time2expl$TotalDurationNear.20cm))/sd(time2expl$TotalDurationNear.20cm) #Standardize so that Zero = average duration spent near tent, negative values = lower duration at times 1 and 2, and positive values = longer durations at times 1 and 2
bothtimeexpl<-rbind(time2expl,time1expl)
boxplot(bothtimeexpl$standTotalDurationNear~bothtimeexpl$FlexGroup)
# DATA CHECKING
library(DHARMa)
library(lme4)
simulationOutput <- simulateResiduals(fittedModel = lmer(log(LatencyFirstLand) ~ FlexGroup + Age + Sex + (1|BirdID), data=exp2), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutput$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
#looks kind of randomly spread
simulationOutput2 <- simulateResiduals(fittedModel = glmer(round(TotalDurationNear.20cm) ~ FlexGroup + Age + Sex + (1|BirdID), family=poisson, data=exp2), n=250)
plot(simulationOutput2$scaledResiduals) # looks a little better
testDispersion(simulationOutput) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation
#p=0.93 so not over or under dispersed
testDispersion(simulationOutput2) #p=0.23
testZeroInflation(simulationOutput) #compare expected vs observed zeros, not zero-inflated if p>0.05
#p=1 No zeros, so not zero inflated
testZeroInflation(simulationOutput2) #p=0.14
testUniformity(simulationOutput) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05.
# p = 0.30, Log-transformed Latency variable and used gaussian distribution
testUniformity(simulationOutput2) #p = 0.81 - Not heteroscedastic
plot(simulationOutput)#...there should be no pattern in the data points in the right panel
plot(simulationOutput2)
#### Assessing repeatability of both Latency to first land AND Duration near the outside of the tent
cor.test(exp2$LatencyFirstLand,exp2$TotalDurationNear.20cm) # they are moderately negatively correlated (r = -0.43)
### UNREGISTERED ANALYSIS: Do grackles perceive the novel environment as threatening? ###
library(MCMCglmm)
prior = list(R=list(R1=list(V=1,nu=0)), G=list(G1=list(V=1,nu=0)))
m1 = MCMCglmm(log(LatencyFirstLand) ~ Condition + FlexGroup + Age + Sex, random=~BirdID, family="gaussian", data=exp, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
autocorr(m1$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(m1$VCV) #Did random effects converge? Yes
summary(m1)
# No difference in performance on Familiar or Novel Environment tests. ß = 0.29, p = 0.27
m2 = MCMCglmm(round(TotalDurationNear.20cm) ~ Condition + FlexGroup + Sex + Age, random=~BirdID, family="poisson", data=exp, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
autocorr(m2$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(m2$VCV) #Did random effects converge? Yes
summary(m2)
# No difference in performance on Familiar or Novel Environment tests. ß = -0.61, p = 0.14
# Only interested in Novel Environment data from here on
### Results qualitatively similar if Age + Sex variable included and no effect on Novel Environment exploration of these variables.
### REGISTERED ANALYSIS: REPEATABILITY ###
#### LatencyFirstLand
#GLMM - 8 Feb 2021: changed family from poisson to gaussian because latency is gaussian, have to log-transform Latency so residuals are normally distributed
prior = list(R=list(R1=list(V=1,nu=0)), G=list(G1=list(V=1,nu=0)))
expl1 <- MCMCglmm(log(LatencyFirstLand) ~ FlexGroup + Age + Sex, random=~BirdID, family="gaussian", data=exp2, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
autocorr(expl1$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(expl1$VCV) #Did random effects converge? Yes
summary(expl1) # FlexGroup is n.s., regardless of whether Sex or Age covariates are included
#Advice from one of our reviewers Maxime Dahirel: In MCMCglmm, the latent scale adjusted repeatability and its credible interval can simply be obtained by: mod$VCV[,ID]/(mod$VCV[,ID]+mod$VCV[,units])
repeata <- expl1$VCV[,"BirdID"]/(expl1$VCV[,"BirdID"]+expl1$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeata) #0.68
var(repeata) #0.02
posterior.mode(repeata) #0.73
HPDinterval(repeata, 0.95) #0.37-0.92
# Addressing Reviewer 5 comment:
expl1.base <- MCMCglmm(log(LatencyFirstLand) ~ 1, random=~BirdID, family="gaussian", data=exp2, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
repeat.base <- expl1.base$VCV[,"BirdID"]/(expl1.base$VCV[,"BirdID"]+expl1.base$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeat.base) #0.68
# from Nakagawa & Schielzeth 2013
mVarF <- var(as.vector(apply(expl1$Sol,2,mean) %*% t(expl1$X)))
mVarF/(mVarF+sum(apply(expl1$VCV,2,mean)))
# alternative with credile intervals
vmVarF<-numeric(1000)
for(i in 1:1000){
Var<-var(as.vector(expl1$Sol[i,] %*% t(expl1$X)))
vmVarF[i]<-Var}
expl1_list <- split(expl1$Sol, seq(nrow(expl1$Sol)))
vmVarF1 <- map(expl1_list, ~.x %*% t(as.matrix(expl1$X))) %>% map_dbl(~var(as.vector(.x)))
table(near(vmVarF, vmVarF1)) # vectors are the same
R2m<-vmVarF/(vmVarF+expl1$VCV[,1]+expl1$VCV[,2])
mean(R2m) # R2 marginal = 0.05
posterior.mode(R2m)
HPDinterval(R2m) # 0 - 0.19
R2c<-(vmVarF+expl1$VCV[,1])/(vmVarF+expl1$VCV[,1]+expl1$VCV[,2] )
mean(R2c) # R2 conditional = 0.71
posterior.mode(R2c)
HPDinterval(R2c) # 0.44-0.91
# Reviewer comment 5: FlexGroup covariate does not account for a significant amount of variance.
#RESULT: LatencyFirstLand (Explore Environment variable) = repeatable, regardless of whether Sex and Age covariates are included
#### TotalDurationNear
prior = list(G=list(G1=list(V=1,nu=1,alpha.mu=0,alpha.V=1000)),
R=list(R1=list(V=1,nu=0.002)))
expl2 <- MCMCglmm(round(TotalDurationNear.20cm) ~ FlexGroup + Age + Sex, random=~BirdID, family="poisson", data=exp2, verbose=F, prior=prior, nitt=130000, thin=100, burnin=3000)
autocorr(expl2$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(expl2$VCV) #Did random effects converge? Yes
summary(expl2) # FlexGroup is n.s., regardless of whether Sex and Age covariates are included
#Advice from one of our reviewers Maxime Dahirel: In MCMCglmm, the latent scale adjusted repeatability and its credible interval can simply be obtained by: mod$VCV[,ID]/(mod$VCV[,ID]+mod$VCV[,units])
repeata <- expl2$VCV[,"BirdID"]/(expl2$VCV[,"BirdID"]+expl2$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeata) #0.85
var(repeata) #0.01
posterior.mode(repeata) #0.93
HPDinterval(repeata, 0.95) #0.67-0.98
# Addressing post study Reviewer comment 5
library(tidyr)
library(purrr)
library(dplyr)
expl2.base <- MCMCglmm(round(TotalDurationNear.20cm) ~ 1, random=~BirdID, family="poisson", data=exp2, verbose=F, prior=prior, nitt=130000, thin=100, burnin=5000)
repeat.base <- expl2.base$VCV[,"BirdID"]/(expl2.base$VCV[,"BirdID"]+expl2.base$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeat.base) #0.89
# from Nakagawa & Schielzeth 2013
mVarF <- var(as.vector(apply(expl2$Sol,2,mean) %*% t(expl2$X)))
mVdis <- log(1 + 1/exp(expl2.base$Sol[,1] + 0.5*(rowSums(expl2.base$VCV))))
mVarF/(mVarF+sum(apply(expl2$VCV,2,mean))+mean(mVdis))
# alternative with crebile intervals
vmVarF<-numeric(1000)
for(i in 1:1000){
Var<-var(as.vector(expl2$Sol[i,] %*% t(expl2$X)))
vmVarF[i]<-Var}
R2m<-vmVarF/(vmVarF+expl2$VCV[,1]+expl2$VCV[,2]+mean(mVdis))
mean(R2m) # R2 marginal = 0.19
posterior.mode(R2m)
HPDinterval(R2m) # 0 - 0.43
R2c<-(vmVarF+expl2$VCV[,1])/(vmVarF+expl2$VCV[,1]+expl2$VCV[,2] + mVdis)
mean(R2c) # R2 conditional = 0.90
posterior.mode(R2c)
HPDinterval(R2c) # 0.76-0.99
# Reviewer comment 5: While FlexGroup does account for some variance, the R squared value is higher in the model including BirdId
#RESULT: TotalDurationNear.20cm (Explore Environment variable) = repeatable, regardless of whether Sex and Age covariates are included.
### UNREGISTERED ANALYSIS - compare R values with rptR function and LRT test to make sure the interpretation of MCMCglmm results is correct - output matches that of MCMCglmm ###
exp2$Name = as.factor(as.character(exp2$Name))
library(rptR)
r1 = rpt(log(LatencyFirstLand) ~ FlexGroup + Age + Sex + (1|Name), grname = "Name", data=exp2, datatype="Gaussian", nboot=1000, npermut=100)
r1
# R = 0.72
# CI = 0.41-0.89
# p < 0.05
r2 = rpt(round(TotalDurationNear.20cm) ~ FlexGroup + Time + Age + Sex + (1|Name), grname = "Name", data=exp2, datatype="Poisson", nboot=1000, npermut=100)
r2
# something weird happening here... SE = 0
exp2$olre = 1:nrow(exp2)
r3 = glmer(round(TotalDurationNear.20cm) ~ FlexGroup + Age + Sex + (1|Name) + (1|olre), family = "poisson", data = exp2)
r4 = glmer(round(TotalDurationNear.20cm) ~ FlexGroup + Age + Sex + (1|olre), family = "poisson", data = exp2)
anova(r3,r4) #Bird ID significantly improves the fit of the model
library(ggplot2)
ggplot(exp2) +
geom_line(aes(x = as.factor(Time), y = TotalDurationNear.20cm, group = BirdID, color = BirdID), size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = TotalDurationNear.20cm, color = BirdID, size = 0.7))
ggplot(exp2) +
geom_line(aes(x = as.factor(Time), y = LatencyFirstLand, group = BirdID, color = BirdID), size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = LatencyFirstLand, color = BirdID, size = 0.7)) +
#facet_grid(.~Condition) +
labs(x = "Time", y = "Latency to approach (sec)") +
theme_bw() +
theme(axis.text = element_text(size = 14),
axis.title = element_text(size = 20),
plot.title = element_text(size = 26),
strip.text.x = element_text(size = 20)) +
ggtitle("Novel Environment Exploration") +
theme(legend.position="none")
## Need to facet by ExpObj data for including in manuscript - in below code chunk.
```
```{r POSTrepeatableExpObj, eval=FALSE, warning=FALSE, include=FALSE, results='asis'}
#Exploration of novel object
eo <- read.csv("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_exploration_data_exploration.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE)
head(eo) #Check to make sure it looks right
#want only Test=Object (not Environment)
eo <- eo[eo$Test=="Object",]
#Sum duration across distances to get DurationOnGround variable as in boldness analysis above
eo$DurationOnGround = eo$TotalDurationInTent + eo$TotalDurationFar.20cm + eo$TotalDurationNear.20cm
#changed LatencyFirstLand NAs to a number higher than the assay session length so they show up as data points? yes. Set latency for these at 3360 (56 minutes: the highest assay duration was 55 mins)
eo$LatencyFirstLand[which(is.na(eo$LatencyFirstLand))]<-3360
eo$LatencyFirstLand <- as.numeric(eo$LatencyFirstLand)
eo$DurationOnGround <- as.numeric(eo$DurationOnGround)
#LatencyFirstLand or Duration has the most data so will use one of these variables.
eo$BirdID <- as.factor(eo$BirdID)
# add column identifying whether bird was in the flexibility manipulation or control groups
d <- read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Preregistrations/g_flexmanip_data_reverse.csv"), header=T, sep=",", stringsAsFactors=F)
d$ID <- as.factor(d$ID)
#remove pilot birds
d <- d[!d$ID=="Fajita" & !d$ID=="Empanada",]
#extract just bird name and flex group
flexID = unique(d[,c(4,5)])
colnames(flexID) = c("Name","FlexGroup")
#Taco did initial discrimination and 1 reversal, so he is considered Control group for this analysis
flexID$FlexGroup[which(flexID$Name == "Taco")]<- "Control"
# Add band ID bird names to data frame to merge it with boldness data
biometrics = read.csv(url("https://raw.githubusercontent.com/corinalogan/grackles/master/Files/Data/data_biometricsAZ.csv"), header=T, sep=",", stringsAsFactors=F)
biometrics = unique(biometrics[,c(1,2,13,14)]) # Include Sex & Age, per Reviewer Comment 34 & 36
flexID = merge(flexID, biometrics, by = "Name")
colnames(eo)[1] <- "Name"
exp.o = merge(eo, flexID, by = "Name", all = T)
# remove NA birds that were in the aviaries but did not complete exploration assays (4 birds)
exp.o = exp.o[-which(is.na(exp.o$Condition)),]
# DATA CHECKING - changed family to gaussian (from poisson) bc latency is gaussian
library(DHARMa)
library(lme4)
simulationOutput <- simulateResiduals(fittedModel = lmer(log(LatencyFirstLand) ~ Condition + FlexGroup + Age + Sex + (1|BirdID), data=exp.o), n=250) #250 simulations, but if want higher precision change n>1000
plot(simulationOutput$scaledResiduals) #Expect a flat distribution of the overall residuals, and uniformity in y direction if plotted against any predictor
#looks flat
exp.o$olre = 1:nrow(exp.o)
simulationOutput2 <- simulateResiduals(fittedModel = glmer(round(DurationOnGround) ~ FlexGroup + (1|BirdID), family=poisson, data=exp.o2), n=250)
plot(simulationOutput2$scaledResiduals) # looks less flat
testDispersion(simulationOutput) #if under- or over-dispersed, then p-value<0.05, but then check the dispersion parameter and try to determine what in the model could be the cause and address it there, also check for zero inflation
#p=0.88 so not over or under dispersed
testDispersion(simulationOutput2) #p=0.90
testZeroInflation(simulationOutput) #compare expected vs observed zeros, not zero-inflated if p>0.05
#p=1 No zeros, so not zero inflated
testZeroInflation(simulationOutput2) #p=0.02 - significantly zero inflated - 11 zeros out of 38 rows
testUniformity(simulationOutput) #check for heteroscedasticity ("a systematic dependency of the dispersion / variance on another variable in the model" Hartig, https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html), which is indicated if dots aren't on the red line and p<0.05.
# p = 0.19, data normally distributed.
testUniformity(simulationOutput2) #p = 0.12
plot(simulationOutput)#...there should be no pattern in the data points in the right panel
# all n.s.
plot(simulationOutput2) # all n.s.
### UNREGISTERED ANALYSIS: Do grackles perceive the novel object as threatening? ###
library(MCMCglmm)
prior = list(R=list(R1=list(V=1,nu=0),R2=list(V=1,nu=0)), G=list(G1=list(V=1,nu=0)))
m1 = MCMCglmm(log(LatencyFirstLand) ~ Condition + FlexGroup, random=~BirdID, family="gaussian", data=exp.o, verbose=F, prior=prior, nitt=500000, thin=500, burnin=5000)
autocorr(m1$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(m1$VCV) #Did random effects converge? Yes, after increasing iterations
summary(m1)
# Grackles took significantly longer to come to the ground for the novel relative to the familiar object. Results are the same if Age and Sex covariates are or are not included.
# ß = 2.11, CI = 1.22-2.89, p < 0.01
m2 = MCMCglmm(round(DurationOnGround) ~ Condition + FlexGroup, random=~BirdID, family="poisson", data=exp.o, verbose=F, prior=prior, nitt=500000, thin=500, burnin=5000)
autocorr(m2$Sol) #Did fixed effects converge? Values after Lag 0 should be < 0.1. Yes
autocorr(m2$VCV) #Did random effects converge? Yes, after increasing iterations
summary(m2)
# Only interested in Novel Object data from here on
exp.o2 = exp.o[-which(exp.o$Condition == "Familiar"),]
### REGISTERED ANALYSIS: REPEATABILITY ###
#GLMM
explo <- MCMCglmm(log(LatencyFirstLand) ~ FlexGroup, random=~BirdID, family="gaussian", data=exp.o2, verbose=F, prior=prior, nitt=6300000, thin=1000, burnin=3000)
summary(explo)
autocorr(explo$Sol) #Did fixed effects converge? Yes=all values after lag 0 are <0.1 indicating they converged
autocorr(explo$VCV) #Did random effects converge? Yes
#In MCMCglmm, the latent scale adjusted repeatability and its credible interval can simply be obtained by: mod$VCV[,ID]/(mod$VCV[,ID]+mod$VCV[,units]) - advice from Maxime Dahirel
repeata <- explo$VCV[,"BirdID"]/(explo$VCV[,"BirdID"]+explo$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeata) #0.01
var(repeata) #0.002
posterior.mode(repeata) #-6.84e-6
HPDinterval(repeata, 0.95) #4.12e-17 to 0.06
# Repeatability on the data/observed scale (accounting for fixed effects)
#code from Supplementary Material S2 from Villemereuil et al. 2018 J Evol Biol
vf <- sapply(1:nrow(explo[["Sol"]]), function(i) {
var(predict(explo, it=i))
}) #estimates for each iteration of the MCMC
repeataF <- (vf+explo$VCV[,"BirdID"])/(vf+explo$VCV[,"BirdID"]+explo$VCV[,"units"]) #latent scale adjusted + data scale
mean(repeataF) #0.04
posterior.mode(repeataF) #0.001
HPDinterval(repeataF, 0.95) #8.20e-9 to 0.14
# Now compare with the raw repeatability: null model
exploraw <- MCMCglmm(log(LatencyFirstLand) ~ 1, random=~BirdID, family="gaussian", data=exp.o2, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
summary(exploraw)
repeataraw <- exploraw$VCV[,"BirdID"]/(exploraw$VCV[,"BirdID"]+exploraw$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeataraw) #0.0002
posterior.mode(repeataraw) #-3.40e-11
HPDinterval(repeataraw, 0.95) #2.90e-17 to 4.62e-6
explo2 <- MCMCglmm(round(DurationOnGround) ~ FlexGroup, random=~BirdID, family="poisson", data=exp.o2, verbose=F, prior=prior, nitt=6300000, thin=1000, burnin=3000)
repeata <- explo2$VCV[,"BirdID"]/(explo2$VCV[,"BirdID"]+explo2$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeata) #0.52
var(repeata) #0.09
HPDinterval(repeata, 0.95) #4.12e-17 to 0.86 - CI is very large, model is a bad fit
#RESULT=Explore Object is not repeatable, regardless of whether Age & Sex covariates are included
### UNREGISTERED ANALYSIS - compare R values with rptR function and LRT test to make sure the interpretation of MCMCglmm results is correct ###
library(rptR)
r2 = rpt(log(LatencyFirstLand) ~ FlexGroup + Age + Sex + (1|BirdID), grname = "BirdID", data=exp.o2, datatype="Gaussian", nboot=1000, npermut=100) # Fit is singular
summary(r2)
# R = 0.05
# CI = 0-0.522
# p = 1
m3 = glmer(log(LatencyFirstLand) ~ FlexGroup + Age + Sex+ (1|BirdID), data = exp.o2, family = gaussian)
m4 = glm(log(LatencyFirstLand) ~ FlexGroup + Age + Sex, data = exp.o2, family = gaussian)
anova(m3,m4) #random effect does not improve the fit of the model, does not account for a significant portion of the variance.
r3 = rpt(round(DurationOnGround) ~ FlexGroup + (1|BirdID), grname = "BirdID", data=exp.o2, datatype="Poisson", nboot=1000, npermut=100) # Fit is singular
summary(r3)
# R = 0.05
# CI = 0-0.522
# p = 1
m3 = glmer(round(DurationOnGround) ~ FlexGroup + (1|BirdID), data = exp.o2, family = poisson)
m4 = glm(round(DurationOnGround) ~ FlexGroup, data = exp.o2, family = poisson)
anova(m3,m4)
# Addressing Reviewer 5 comment:
explo.base <- MCMCglmm(log(LatencyFirstLand) ~ 1, random=~BirdID, family="gaussian", data=exp.o2, verbose=F, prior=prior, nitt=13000, thin=10, burnin=3000)
repeat.base <- explo.base$VCV[,"BirdID"]/(explo.base$VCV[,"BirdID"]+explo.base$VCV[,"units"]) #latent scale adjusted repeatability and its credible interval
mean(repeat.base) #0.02
# from Nakagawa & Schielzeth 2013
mVarF <- var(as.vector(apply(explo$Sol,2,mean) %*% t(explo$X)))
mVarF/(mVarF+sum(apply(explo$VCV,2,mean)))
# alternative with credile intervals
vmVarF<-numeric(1000)
for(i in 1:1000){
Var<-var(as.vector(explo$Sol[i,] %*% t(explo$X)))
vmVarF[i]<-Var}
explo_list <- split(explo$Sol, seq(nrow(explo$Sol)))
vmVarF1 <- map(explo_list, ~.x %*% t(as.matrix(explo$X))) %>% map_dbl(~var(as.vector(.x)))
table(near(vmVarF, vmVarF1))
R2m<-vmVarF/(vmVarF+explo$VCV[,1]+explo$VCV[,2])
mean(R2m) # R2 marginal = 0.10
posterior.mode(R2m)
HPDinterval(R2m) # 0 - 0.24
R2c<-(vmVarF+explo$VCV[,1])/(vmVarF+explo$VCV[,1]+explo$VCV[,2] )
mean(R2c) # R2 conditional = 0.11
posterior.mode(R2c)
HPDinterval(R2c) # 0 - 0.28
# Reviewer comment 5: FlexGroup covariate accounts for a significant amount of variance.
#### CONTEXTUAL REPEATABILITY - combine explore environment and explore object back together. Only novel condition
exp2$DurationOnGround = exp2$TotalDurationInTent + exp2$TotalDurationFar.20cm + exp2$TotalDurationNear.20cm
exp.both = rbind(exp2, exp.o2)
rptBoth = rpt(log(LatencyFirstLand) ~ Test + FlexGroup + (1|BirdID), grname = "BirdID", data=exp.both, datatype="Gaussian", nboot=1000, npermut=100)
summary(rptBoth) # R = 0.49, CI = 0.21-0.69, p = 0
rptBoth2 = rpt(log(LatencyFirstLand) ~ FlexGroup + (1|BirdID), grname = "BirdID", data=exp.both, datatype="Gaussian", nboot=1000, npermut=100)
summary(rptBoth2) #no difference in repeatability if we don't control for Test - in other words, the between-individual variance is the same regardless of which test
xcontx = lmer(log(LatencyFirstLand) ~ Test + FlexGroup+ Age + Sex+ (1|BirdID), data = exp.both)
car::Anova(xcontx) #grackles take longer to land in the presence of the object relative to the environment
# Supplementary figure 1
library(ggplot2)
ggplot(exp, aes(x = as.factor(Time), y = LatencyFirstLand, colour = BirdID, shape = Test)) +
geom_point(size = 3) +
facet_wrap( ~ BirdID) +
labs(x = "Time", y = "Latency to approach (sec)") +
theme_bw() +
scale_colour_discrete(guide = "none")
# Figure 3
exp.o2$FlexGroup=factor(exp.o2$FlexGroup, levels = c("Control","Manipulation"), labels = c("Control","Trained"))
eelatency = ggplot(exp2) +
geom_line(aes(x = as.factor(Time), y = LatencyFirstLand, group = BirdID, color = BirdID, shape = FlexGroup),
size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = LatencyFirstLand, color = BirdID, shape = FlexGroup, size = 0.7, alpha = 0.7)) +
#facet_grid(.~Test) +
labs(y = "Latency to approach (sec)") +
theme_bw() +
theme(axis.text = element_text(size = 14),
axis.text.x = element_blank(),
axis.title.y = element_text(size = 20),
axis.title.x = element_blank(),
plot.title = element_text(size = 26),
strip.text.x = element_text(size = 20)) +
theme(legend.title = element_text(size=16), #change legend title font size
legend.text = element_text(size=14)) + #change legend text font size
labs(title = "Novel Environment") +
guides(color = FALSE, shape = F,alpha = F, size = F)
eolatency = ggplot(exp.o2) +
geom_line(aes(x = as.factor(Time), y = LatencyFirstLand, group = BirdID, color = BirdID, shape = FlexGroup),
size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = LatencyFirstLand, color = BirdID, shape = FlexGroup, size = 0.7, alpha = 0.7)) +
#facet_grid(.~Test) +
labs(y = "Latency to approach (sec)") +
theme_bw() +
theme(axis.text = element_text(size = 14),
#axis.text.y = element_blank(),
axis.text.x = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
plot.title = element_text(size = 26),
strip.text.x = element_text(size = 20)) +
theme(legend.title = element_text(size=16), #change legend title font size
legend.text = element_text(size=14)) + #change legend text font size
labs(title = "Novel Object") +
guides(color = FALSE, shape = F,alpha = F, size = F)
eduration = ggplot(exp.o2) +
geom_line(aes(x = as.factor(Time), y = DurationOnGround, group = BirdID, color = BirdID,
shape = FlexGroup), size = 1.8, alpha = 0.7) +
geom_point(aes(x = as.factor(Time), y = DurationOnGround, color = BirdID,
shape = FlexGroup, size = 1.8, alpha = 0.7)) +
labs(x = "Time", y="Duration near (sec)") +
theme_bw() +
theme(axis.text = element_text(size = 14),
axis.title.y = element_text(size = 20),
axis.title.x = element_text(size = 20),
plot.title = element_text(size = 26),
strip.text.x = element_blank()) +
guides(color = "none", alpha = "none", size = "none",
shape= "none")
#Only add these to run eduration plot to save the shared legend, using 'leg' code below that is otherwise hashtagged out.
#guide_legend(title="Serial reversal \n learning group", override.aes=list(size=5))) +
# theme(legend.title = element_text(size=20), #change legend title font size
# legend.text = element_text(size=18)) + #change legend text font size
#theme(legend.position="right")
library(gridExtra)
#leg = get_legend(eduration)
#as_ggplot(leg)
#only use these for generating the shared legend, when code from eduration plot is not hashtagged
ggarrange(eelatency, eolatency, eduration, leg, align = "hv")