-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChapter3.Rtex
2708 lines (1764 loc) · 124 KB
/
Chapter3.Rtex
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
%--------------------------------------------------------------------------------------------------------------------------------%
% Code and text for "A comparative test of the role of population structure in determining pathogen richness"
% Chapter 2 of thesis "The role of population structure and size in determining bat pathogen richness"
% by Tim CD Lucas
%
% NB The file is numbered Chapter3 as this was previously Chapter 3 in the thesis.
%
%---------------------------------------------------------------------------------------------------------------------------------%
%%begin.rcode settings, echo = FALSE, cache = FALSE, message = FALSE, results = 'hide', eval = TRUE
##################################
### Run web scraping? ###
##################################
# There's some slow webscrapping functions. Run them?
runPubmedScrape <- FALSE
runScholarScrape <- FALSE
runFstScrape <- FALSE
# Run slow bootstrapping?
subBoots <- FALSE
fstBoots <- FALSE
batclocksBoots <- FALSE
# Run slow fst data wrangling as some is slow.
fstComb <- FALSE
runIucn <- FALSE
# There are figures created in the data analysis which are not in the final chapter document.
# If TRUE, they will be included in the output.
# Use 'hide' to remove them.
extraFigs <- 'hide'
#knitr options
opts_chunk$set(cache.path = '.Ch3Cache/')
source('misc/KnitrOptions.R')
# ggplot2 theme.
source('misc/theme_tcdl.R')
theme_set(theme_grey() + theme_tcdl)
# Choose the number of cores to use
nCores <- 4
%%end.rcode
%%begin.rcode libs, cache = FALSE, result = FALSE
# Data handling
library(dplyr)
library(broom)
library(readxl)
library(sqldf)
library(reshape2)
# phylogenetic regression
library(ape)
library(caper)
library(phytools)
library(nlme)
library(qpcR)
library(car)
# weighted means + var
library(Hmisc)
# Plotting
library(ggplot2)
library(ggtree)
library(palettetown)
library(ggthemes)
library(GGally)
library(cowplot)
# Web scraping.
library(rvest)
# For synonym list
library(taxize)
# Spatial analysis
library(maptools)
library(geosphere)
# Parllel computation
library(parallel)
%%end.rcode
%%begin.rcode parameters
# Define some parameters.
# This is useful at the top so that it can go in text.
# How many bootstraps for model selection NULL variable
nBoots <- 50
# What proportion of a species range should be covered for an Fst study to count as valid.
rangeUseable <- 0.20
%%end.rcode
\section{Abstract}
%\tmpsection{One or two sentences providing a basic introduction to the field}
% comprehensible to a scientist in any discipline.
\lettr{Z}oonotic diseases make up the majority of human infectious diseases and are a major drain on healthcare resources and economies.
Species that host many pathogen species are more likely to be the source of a novel zoonotic disease than species with few pathogens, all else being equal.
However, the factors that influence pathogen richness in animal species are poorly understood.
%
%
%\tmpsection{Two to three sentences of more detailed background}
% comprehensible to scientists in related disciplines.
% Theory led.
The pattern of contacts between individuals (i.e.\ population structure) can be influenced by habitat fragmentation, sociality and dispersal behaviour.
Epidemiological theory suggests that increased population structure can promote pathogen richness by reducing competition between pathogen species.
Conversely, it is often assumed that as greater population structure slows the spread of a new pathogen (i.e.\ lowers $R_0$), less structured populations should have greater pathogen richness.
%
%
%\tmpsection{One sentence clearly stating the general problem (the gap)}
% being addressed by this particular study.
Previous comparative studies comparing pathogen richness and population structure measured population structure differently and have had contradictory results, complicating the interpretation.
%
%
%\tmpsection{One sentence summarising the main result}
% (with the words “here we show” or their equivalent).
Here I test whether increased population structure correlates with viral richness using comparative data across 203 bat species, controlling for body mass, geographic range size, study effort and phylogeny.
This is an indirect test between the two competing hypotheses: does increased population structure allow pathogen coexistence by reducing competition, or does increased population structure decrease $R_0$ and therefore cause fewer new pathogens to enter the population.
Bats, as a group, make a useful case study because they have been associated with a number of important, recent zoonotic outbreaks.
Unlike previous studies, I used two measures of population structure: the number of subspecies and effective levels of gene flow.
I find that both measures are positively associated with pathogen richness.
%
%
%\tmpsection{Two or three sentences explaining what the main result reveals in direct comparison to what was thoughts to be the case previously}
% or how the main result adds to previous knowledge
My results add more robust support to the hypothesis that increased population structure promotes viral richness in bats.
The results support the prediction that increased population structure allows greater pathogen richness by reducing competition between pathogens.
The prediction that factors that decrease $R_0$ should decrease pathogen richness is not supported.
%
%
%\tmpsection{One or two sentences to put the results into a more general context.}
Although my analysis implies that increased population structure does promote pathogen richness in bats, the weakness of the relationship and the difficulty in obtaining some measurements means that this is probably not a useful, predictive factor on its own for optimising zoonotic surveillance.
%However, the relationship has implications for global change, implying that increased habitat fragmentation might promote greater viral richness in bats.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Introduction}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%#the introduction is not bad and starts very well but i think you need a bit more from studies of other mammals (not bats) to put the study into context as well as explaining why particularly you focus on pop structure, some justification of why bats, and less detail about the specific Fst measures (move to methods) and more stuff on your actual methods and approach you use in this study.
%#Structure could be:
%#1. Zoonotic disease is bad (as you have written it already)
%#2. Need to understand why some species have more pathogens than others. Life history variables of the host have been used to explain why some species have more than others, such as blah blah. However, pop structure (explain what this means) is of particular interest because of blah blah.
%#3. Epidemiological theoretical models predict relationship with pop structure and translated into across species patterns as increased structure less pathogen diversity but problem is of inter-pathogen competition
%#4. lack of large across species studies of these relationships - those that have been done have conflicting patterns (examples across different taxa).
%#5. Bats are very interesting in this regard because of blah
%#6. Bat studies of pathogen richness and population structure are particularly interesting in this area but also are conflicting (examples), due in part to low sample sizes and problems with comparing results using different definitions of population structure and not controlling for effects of phylogeny.
%#7. Here I use a phylogenetic comparative approach to understand the relationship between pop structure and pathogen richness across the largest study of bats to date. I use a phylogenetic GLM controlling for the other life history characteristics known to impact pathogen richness to quantify the relationship between viral richness (as a proxy for pathogen richness_ and two measures of population structure.
%#8. I found ...
\tmpsection{General Intro}
%#1. Zoonotic disease is bad (as you have written it already)
Zoonotic pathogens make up the majority of newly emerging diseases and have profound consequences for public health, economics and international development \cite{jones2008global, smith2014global, ebolaWorldbank}.
Better statistical models for predicting which wild host species are potential reservoirs of zoonotic diseases would allow us to optimise zoonotic disease surveillance and anticipate how the risks of disease spillover might change with global change.
The chance that a host species will be the source of a zoonotic pathogen depends on a number of factors, such as its proximity and interactions with humans, the prevalence of its pathogens and the number of pathogen species it carries \cite{wolfe2000deforestation}.
However, the factors that control the number of pathogen species a host species carries remain poorly understood.
\tmpsection{Specific Intro}
%#2. Need to understand why some species have more pathogens than others. Life history variables of the host have been used to explain why some species have more than others, such as blah blah.
\tmpsection{Theoretical background}
A number of species traits that might control pathogen richness have been studied.
These traits can be at the level of the individual (e.g., body mass and longevity) or the level of the population (e.g., population density, sociality and species range size).
Large bodied animals have been shown to have high pathogen richness with large bodies providing more resources for pathogens \cite{kamiya2014determines, arneberg2002host, poulin1995phylogeny, bordes2008bat, luis2013comparison}.
Long lived species are expected to have high pathogen richness because the number of pathogens a host encounters in its lifetime will be higher \cite{nunn2003comparative, ezenwa2006host, luis2013comparison}.
Animal density \cite{kamiya2014determines, nunn2003comparative, arneberg2002host} and sociality \cite{bordes2007rodent, vitone2004body, altizer2003social, ezenwa2006host} are both predicted to increase pathogen richness by increasing the rate of spread, $R_0$, of a new pathogen.
Finally, widely distributed species have high pathogen richness, potentially because they experience a wider range of environments or because they are sympatric with more species \cite{kamiya2014determines, nunn2003comparative, luis2013comparison}.
%# However, pop structure (explain what this means) is of particular interest because of blah blah.
%#3. Epidemiological theoretical models predict relationship with pop structure and translated into across species patterns as increased structure less pathogen diversity but problem is of inter-pathogen competition
A further population level factor that may affect pathogen richness is population structure.
Population structure can be defined as the extent to which interactions between individuals in a population are non-random.
The role of population structure on human epidemics has been studied in depth and it has been shown that decreased population structure increases the speed of pathogen spread and makes establishment of a new pathogen more likely \cite{colizza2007invasion, vespignani2008reaction}.
In comparative studies of pathogen richness in wild animals, this relationship with $R_0$ is often taken as a prediction that decreased population structure will increase pathogen richness relative to other host species \cite{nunn2003comparative, morand2000wormy, poulin2014parasite, poulin2000diversity, altizer2003social}.
However, epidemiological models of highly virulent pathogens have shown that increased population structure can allow persistence of a pathogen where a well-mixed population would experience a single, large epidemic followed by pathogen extinction \cite{blackwood2013resolving, plowright2011urban}.
Furthermore, the assumption that high $R_0$ leads to high pathogen richness ignores inter-pathogen competition.
Simple epidemiological models of competition between multiple pathogens show that, in completely unstructured populations, a competitive exclusion process occurs but that adding population structure makes coexistence possible \cite{qiu2013vector, allen2004sis, nunes2006localized}.
\tmpsection{Previous Studies}
%#4. lack of large across species studies of these relationships - those that have been done have conflicting patterns (examples across different taxa).
There is a lack of large, comparative studies of the role of population structure on pathogen richness.
Sociality, which is one constituent part of population structure, has been well studied.
However, in primates only a weak positive association between sociality and pathogen richness was found \cite{vitone2004body}.
Furthermore, a negative association was found in rodents \cite{bordes2007rodent} and in even and odd-toed hoofed mammals \cite{ezenwa2006host}.
Finally, two studies tested for an association between group size and parasite richness in bats \cite{bordes2008bat, gay2014parasite}.
Amongst 138 bat species, \textcite{bordes2008bat} found no relationship between group size (coded into four classes) and bat fly species richness.
\textcite{gay2014parasite} found a negative relationship between colony size and viral richness but a positive relationship between colony size and ectoparasite richness.
While sociality is an important component of population structure it does not capture fully how connected the population is globally.
%#5. Bats are very interesting in this regard because of blah
%#6. Bat studies of pathogen richness and population structure are particularly interesting in this area but also are conflicting (examples), due in part to low sample sizes and problems with comparing results using different definitions of population structure and not controlling for effects of phylogeny.
Three studies have used comparative data to test for an association between global population structure and viral richness in bats.
A study on 15 African bat species found a positive relationship between the extent of distribution fragmentation and viral richness \cite{maganga2014bat}.
Conversely, a study on 20 South-East Asian bat species found the opposite relationship \cite{gay2014parasite}.
These studies used the ratio between the perimeter and area of the species' geographic range as their measure of population structure.
However, range maps are very coarse for many species.
Furthermore, range maps are likely to be more detailed (and therefore have a greater perimeter) in well studied species.
A global study on 33 bat species found a positive relationship between $F_{ST}$ --- a measure of genetic structure --- and viral richness \cite{turmelle2009correlates}.
However, this study included measures using mtDNA which only measures female dispersal which may have biased the results as many bat species show female philopatry \cite{kerth2002extreme, hulva2010mechanisms}.
Furthermore, this study used measures of $F_{ST}$ irrespective of the spatial scale of the study including studies covering from tens \cite{mccracken1981social} to thousands \cite{petit1999male} of kilometres.
As isolation by distance has been shown in a number of bat species \cite{burland1999population, hulva2010mechanisms, o2015genetic, vonhof2015range}, this could bias results further.
Finally, when a global $F_{ST}$ value is not given, \textcite{turmelle2009correlates} used the mean of all pairwise $F_{ST}$ values between sites.
This is not correct as pairwise and global $F_{ST}$ values have different relationships with effective migration rates.
\tmpsection{The gap}
\tmpsection{What I did/found}
%#7. Here I use a phylogenetic comparative approach to understand the relationship between pop structure and pathogen richness across the largest study of bats to date. I use a phylogenetic GLM controlling for the other life history characteristics known to impact pathogen richness to quantify the relationship between viral richness (as a proxy for pathogen richness_ and two measures of population structure.
%#8. I found ...
Here I used a phylogenetic comparative approach to test for a relationship between increased population structure and pathogen richness in the largest study of bats to date.
I used phylogenetic linear models, controlling for the other life history characteristics known to impact pathogen richness, to quantify the relationship between viral richness (as a proxy for pathogen richness) and two measures of population structure: the number of subspecies and effective gene flow.
I used two measures of population structure to increase the robustness of the analysis; this is particularly important as previous studies have had contradictory results \cite{maganga2014bat, gay2014parasite, turmelle2009correlates}.
I found that increases in both measures of population structure are positively associated with viral richness and are included as explanatory variables in the best models for describing viral richness.
Furthermore, I found that the role of phylogeny is very weak both in the models and in the distribution of viral richness amongst taxa.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Methods}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Data Collection}
\subsubsection{Pathogen richness}
To measure pathogen richness I used data from \textcite{luis2013comparison}.
This data simply includes known infections of a bat species with a virus species.
I have used viral richness as a proxy for pathogen richness more generally.
Rows with host species that were not identified to species level according to \textcite{wilson2005mammal} were removed.
Many viruses were not identified to species level or their specified species names were not in the ICTV virus taxonomy \cite{ICTV}.
Therefore, I counted a virus if it was the only virus, for that host species, in the lowest taxonomic level identified (present in the ICTV taxonomy).
For example, if a host is recorded as harbouring an unknown Paramyxoviridae virus, then it is logical to assume that the host carries at least one Paramyxoviridae virus.
If a host carries an unknown Paramyxoviridae virus and a known Paramyxoviridae virus, it is hard to confirm that the unknown virus is not another record of the known virus.
In this case, the host would be counted as having one virus species.
%$F_{ST}$ studies are conducted at a range of spatial scales, but $F_{ST}$ often increases with distance studied \cite{burland1999population, hulva2010mechanisms, o2015genetic, vonhof2015range}.
%To minimise the effects of this I only used data from studies that cover \rinline{rangeUseable * 100}\% of the diameter of the species range.
%This is a largely arbitrary value that could be considered to reflect a ``global'' estimate of $F_{ST}$ while keeping a reasonable number of data points available.
%I calculated the diameter of the species range by finding the furthest apart points in the IUCN species range \cite{iucn} even if the range is split into multiple polygons.
%The width covered by each study was the distance between the most distant sampling sites.
%When this was not explicit in the paper, the centre of the lowest level of geographic area was used.
%%begin.rcode luis2013virusRead
#read in luis2013virus data
virus2 <- read.csv('data/Chapter3/luis2013comparison.csv', stringsAsFactors = FALSE)
virus2$binomial <- paste(virus2$host.genus, virus2$host.species)
# From methods
#Many viruses were not identified to species level or their identified species was not in the ICTV virus taxonomy \cite{ICTV}.
#I counted a virus if it was the only virus, for that host species, in the lowest taxonomic level identified in the ICTV taxonomy.
#That is, if a host carries an unknown Paramyxoviridae virus, then it must carry at least one Paramyxoviridae virus.
#If a host carries an unknown Paramyxoviridae virus and a known Paramyxoviridae virus, then it is hard to confirm that the unknown virus is not another record of the known virus.
#In this case, this would be counted as one virus species.
# This has been implemented manually and indicated in the column `remove`
virus2 <- virus2[!virus2$remove, ]
%%end.rcode
%%begin.rcode wilsonReaderTaxonomyRead, fig.show = extraFigs, fig.cap = 'Histogram of number of subspecies'
##################################################################
### Subspecies vs Viruses analysis. ###
##################################################################
# Read in the wilson Reader Taxonomy and use it to calculate the number of subspecies each bat species has.
tax <- read.csv('data/Chapter3/msw3-all.csv', stringsAsFactors = FALSE)
chir <- tax %>%
filter(Order == 'CHIROPTERA')
# Save some memory.
rm(tax)
# Count the number of subspecies each bat species has.
subs <- sqldf('
SELECT Family, Genus, Species, COUNT(Subspecies)
AS NumberOfSubspecies
FROM chir
Where Species <> ""
GROUP BY Genus, Species
')
# I think each species has 1 row for species and extra rows for subspecies
# Check this is true.
# If that is correct, then Species with >1 NumberOfSubspecies should be one less.
SpeciesRows <- sqldf('
SELECT Genus, Species, COUNT(Subspecies)
AS SpeciesRows
FROM chir
WHERE Subspecies == "" AND Species <> ""
GROUP BY Genus, Species
')
#
(SpeciesRows$SpeciesRows != 1) %>% sum
all(SpeciesRows$SpeciesRows == 1)
# Species with >1 NumberOfSubspecies should be one less
subs$NumberOfSubspecies <- ifelse(subs$NumberOfSubspecies > 1,
subs$NumberOfSubspecies - 1,
subs$NumberOfSubspecies)
# Quick look at species with highest number of subspecies.
subs[order(subs$NumberOfSubspecies, decreasing = TRUE ),] %>% head
# Megaderma spasma is top. It's widespread across south east asia islands.
# So this makes sense.
# Quick look at the number of subspecies.
ggplot(subs, aes(x = NumberOfSubspecies)) +
geom_histogram(binwidth = 2) +
xlab('Number of Subspecies') +
ylab('Count')
# Create a combined binomial name column
subs$binomial <- paste(subs$Genus, subs$Species)
# Check overlap of datasets.
sum(!(virus2$binomial[virus2$host.species != ''] %in% subs$binomial))
notInTax <- (virus2$binomial[virus2$host.species != ''])[!(virus2$binomial[virus2$host.species != ''] %in% subs$binomial)]
# Run this to find synonyms of names not in Wilson and Reeder
# Doesn't find much of use.
# syns <- synonyms(notInTax, db = 'itis')
# Clean some names
# As taxize::synonyms didn't find most of them, I am using IUCN.
# And checking that the IUCN name is then in The Wilson & Reeder taxonomy
virus2$binomial[virus2$binomial == 'Myotis pilosus'] <- 'Myotis ricketti'
virus2$binomial[virus2$binomial == 'Tadarida pumila'] <- 'Chaerephon pumilus'
virus2$binomial[virus2$binomial == 'Tadarida condylura'] <- 'Mops condylurus'
virus2$binomial[virus2$binomial == 'Rhinolophus hildebrandti'] <- 'Rhinolophus hildebrandtii'
# Rhinolophus horsfeldi: I can't find this species anywhere. Will exclude.
# Possibly Megaderma spasma according to http://www.fao.org/3/a-i2407e.pdf
virus2$binomial[virus2$binomial == 'Tadarida plicata'] <- 'Chaerephon plicatus'
virus2$binomial[virus2$binomial == 'Artibeus planirostris'] <- 'Artibeus jamaicensis'
sum(!(virus2$binomial[virus2$host.species != ''] %in% subs$binomial))
%%end.rcode
%%begin.rcode subsHistsByFam, fig.show = extraFigs, fig.height = 3, fig.cap = 'Histograms of number of subspecies for the families with many species.'
# Compare the histograms of numbers of subspecies over the families with many species.
subs %>%
filter(Family %in% names(which(table(subs$Family) > 99))) %>%
ggplot(., aes(x = NumberOfSubspecies, y = ..density..)) +
geom_histogram() +
facet_grid(. ~ Family) +
xlab('Number of Subspecies') +
ylab('Density')
%%end.rcode
%%begin.rcode, subvsvirusCaption
# Caption for subspecies vs n. viruses plot.
subvsvirus <- '
Number of viruses against number of subspecies.
Points are coloured by family, with families with less than 10 species being grouped into "other".
Contours show the 2D density of points and suggest a positive correlation.
'
subvsvirusTitle <- 'Number of viruses against number of subspecies'
%%end.rcode
%%begin.rcode subsDataFrame, fig.show = extraFigs, fig.cap = subvsvirus, fig.scap = subvsvirusTitle, out.width = '\\textwidth'
# create combined dataframe
# Join dataframes
species <- sqldf("
SELECT subs.binomial, virus2.[virus.species]
FROM subs
INNER JOIN virus2
ON subs.binomial=virus2.binomial;
")
# Count number of virus species for each bat species
nSpecies <- species %>%
unique %>%
group_by(binomial) %>%
summarise(virusSpecies = n())
# Add other Subspecies data.
nSpecies <- sqldf("
SELECT nSpecies.binomial, virusSpecies, NumberOfSubspecies, Genus, Family
FROM nSpecies
LEFT JOIN subs
ON nSpecies.binomial=subs.binomial
")
# Create another column to make plotting easier.
# Group families with few rows into 'other'
nSpecies$familyPlotCol <- nSpecies$Family
nSpecies$familyPlotCol[
nSpecies$Family %in% names(which(table(nSpecies$Family) < 10))] <- 'Other'
table(nSpecies$familyPlotCol)
ggplot(nSpecies, aes(x = log(NumberOfSubspecies), y = log(virusSpecies))) +
# geom_smooth(method = 'lm') +
geom_jitter(aes(colour = familyPlotCol), size = 2.5, alpha = 0.8,
position = position_jitter(width = .1, height = .1)) +
scale_colour_hc() +
geom_density2d() +
labs(colour = 'Family')
%%end.rcode
%%begin.rcode virusHist, fig.show = extraFigs, fig.cap = 'Histogram of known viruses per species'
ggplot(nSpecies, aes(x = virusSpecies)) +
geom_histogram()
%%end.rcode
%%begin.rcode euthRead
# Read in pantheria data base
pantheria <- read.table(file = 'data/Chapter3/PanTHERIA_1-0_WR05_Aug2008.txt',
header = TRUE, sep = "\t", na.strings = c("-999", "-999.00"))
mass <- sqldf("
SELECT [X5.1_AdultBodyMass_g]
FROM nSpecies
LEFT JOIN pantheria
ON nSpecies.binomial=pantheria.MSW05_Binomial
")
nSpecies$mass <- mass[, 1]
# Now add additional mass estimates.
additionalMass <- read.csv('data/Chapter3/AdditionalBodyMass.csv', stringsAsFactors = FALSE)
meanAdditionalMass <- additionalMass %>%
group_by(binomial) %>%
summarise(mass = mean(Body.Mass.grams))
nSpecies$mass[
sapply(meanAdditionalMass$binomial, function(x) which(nSpecies$binomial == x))
] <- meanAdditionalMass$mass
%%end.rcode
%%begin.rcode IUCNranges, eval = runIucn
# Read in iucn ranges and calculate range sizes for each species.
ranges <- readShapePoly('data/Chapter3/TERRESTRIAL_MAMMALS/TERRESTRIAL_MAMMALS.shp')
ranges <- ranges[ranges$order_name == 'CHIROPTERA', ]
levels(ranges$binomial) <- c(levels(ranges$binomial), 'Myotis ricketti')
ranges$binomial[ranges$binomial == 'Myotis pilosus'] <- 'Myotis ricketti'
nSpecies$binomial[!(nSpecies$binomial %in% ranges$binomial)]
findArea <- function(name){
#cat(name)
A <- areaPolygon(ranges[ranges$binomial == name, ])
sum(A)
}
iucnDistr <- sapply(nSpecies$binomial, findArea)
write.csv(iucnDistr, 'data/Chapter3/iucnDistr.csv')
%%end.rcode
%%begin.rcode readIucnIn
iucnDistr <- read.csv('data/Chapter3/iucnDistr.csv', row.names = 1)
nSpecies$distrSize <- iucnDistr$x
%%end.rcode
%%begin.rcode pubmedScrapeFunc
# Scrape from pubmed
scrapePub <- function(sp){
Sys.sleep(2)
# Initialise refs
refs <- NA
# Find synonyms from taxize
syns <- synonyms(sp, db = 'itis')
if(NROW(syns[[1]]) == 1){
spString <- tolower(gsub(' ', '%20', sp))
} else {
spString <- paste(tolower(gsub(' ', '%20', syns[[1]]$syn_name)), collapse = '%22+OR+%22')
}
url <- paste0('http://www.ncbi.nlm.nih.gov/pubmed/?term=%22', spString, '%22')
page <- html(url)
# Test if exact phrase was found.
phraseFound <- try(page %>%
html_node('.icon') %>%
html_text() %>%
grepl("The following term was not found in PubMed:", .), silent = TRUE)
if (class(phraseFound) == "logical") {
if(phraseFound){
if(phraseFound) refs <- NA
}
}
if (class(phraseFound) != "logical") {
try({
refs <- page %>%
html_node('.result_count') %>%
html_text() %>%
strsplit(' ') %>%
.[[1]] %>%
.[length(.)] %>%
as.numeric()
})
}
return(refs)
}
%%end.rcode
%%begin.rcode pubmedScrape, eval = runPubmedScrape
# Create empty vector
pubmedRefs <- rep(NA, nrow(nSpecies))
for(i in 1:NROW(nSpecies)){
pubmedRefs[i] <- scrapePub(nSpecies$binomial[i])
}
pubmedScrapeDate <- Sys.Date()
pubmedRefs <- cbind(binomial = nSpecies$binomial, pubmedRefs = pubmedRefs)
# Write out.
write.csv(pubmedRefs, file = 'data/Chapter3/pubmedRefs.csv')
%%end.rcode
%%begin.rcode pubmedRead
pubmedRefs <- read.csv('data/Chapter3/pubmedRefs.csv', stringsAsFactors = FALSE, row.names = 1)
# Function returns NA for none found. Change that to a zero.
pubmedRefs$pubmedRefs[is.na(pubmedRefs$pubmedRefs)] <- 0
nSpecies$pubmedRefs <- pubmedRefs$pubmedRefs
%%end.rcode
%%begin.rcode scholarScrapeFunc
scrapeScholar <- function(sp){
wait <- rnorm(1, 120, 2)
Sys.sleep(wait)
syns <- synonyms(sp, db = 'itis')
if(NROW(syns[[1]]) == 1){
spString <- tolower(gsub(' ', '%20', sp))
} else {
spString <- paste(tolower(gsub(' ', '%20', syns[[1]]$syn_name)), collapse = '%22+OR+%22')
}
url <- paste0('https://scholar.google.co.uk/scholar?hl=en&q=%22',
spString, '%22&btnG=&as_sdt=1%2C5&as_sdtp=')
page <- html(url)
try({
refs <- page %>%
html_node('#gs_ab_md') %>%
html_text() %>%
gsub('About\\s(.*)\\sresults.*', '\\1', .) %>%
gsub(',', '', .) %>%
as.numeric
})
return(refs)
}
%%end.rcode
%%begin.rcode scholarScrape, eval = runScholarScrape
# Create empty vector
scholarRefs <- rep(NA, nrow(nSpecies))
for(i in 1:NROW(nSpecies)){
scholarRefs[i] <- scrapeScholar(nSpecies$binomial[i])
}
scholarScrapeDate <- Sys.Date()
scholarRefs <- cbind(binomial = nSpecies$binomial, scholarRefs = scholarRefs)
# Write out.
write.csv(scholarRefs, file = 'data/Chapter3/scholarRefs.csv')
%%end.rcode
%%begin.rcode scholarRead
scholarRefs <- read.csv('data/Chapter3/scholarRefs.csv', stringsAsFactors = FALSE, row.names = 1)
# Function returns NA for none found. Change that to a zero.
scholarRefs$scholarRefs[is.na(scholarRefs$scholarRefs)] <- 0
nSpecies$scholarRefs <- sqldf('
SELECT scholarRefs
FROM nSpecies
INNER JOIN scholarRefs
ON scholarRefs.binomial=nSpecies.binomial
'
) %>%
.$scholarRefs
%%end.rcode
%%begin.rcode subsRemoveNAs
# Remove missing data and sort out the data frame a little.
nSpecies <- nSpecies[complete.cases(nSpecies), ]
# Add number of subspecies as a factor. Might help plotting.
nSpecies$SubspeciesFactor <- factor(nSpecies$NumberOfSubspecies,
levels = as.character(1:max(nSpecies$NumberOfSubspecies)))
# Rownames to species names
rownames(nSpecies) <- nSpecies$binomial
%%end.rcode
%%begin.rcode savenSpecies
########################################################
### At this point, nSpecies should be in final form ###
########################################################
write.csv(nSpecies, file = 'data/Chapter3/nSpecies.csv')
%%end.rcode
%%begin.rcode treeRead
# Read in trees
t <- read.nexus('data/Chapter3/fritz2009geographical.tre')
# Select best supported tree
tr1 <- t[[1]]
# Make names match previous names
tr1$tip.label <- gsub('_', ' ', tr1$tip.label)
# Which tips are not needed
unneededTips <- tr1$tip.label[!(tr1$tip.label %in% nSpecies$binomial)]
# Prune tree down to only needed tips.
pruneTree <- drop.tip(tr1, unneededTips)
rm(t)
%%end.rcode
%%begin.rcode nSpeciesTreePlot, out.width = '\\textwidth', fig.cap = 'Pruned phylogeny with dot size showing number of pathogens and colour showing family.', fig.show = extraFigs
# Plot tree
p <- ggtree(pruneTree, layout = 'fan')
p %<+% nSpecies[, 1:6] +
geom_point2(aes(size = virusSpecies, colour = Family, subset = isTip)) +
scale_size(range = c(0.2, 2)) +
scale_colour_manual(values = c(pokepal('oddish')[c(1,3,5,6,9,10)], pokepal('Carvanha')[c(1,2,4, 13, 12)])) +
theme_tcdl +
theme(plot.margin = unit(c(-1, 3, -2.5, -2), "lines")) +
theme(legend.position = 'right') +
labs(size = 'Virus Richness') +
theme(legend.key.size = unit(0.6, "lines"),
legend.text = element_text(size = 6),
legend.title = element_text(size = 8))
%%end.rcode
%%begin.rcode scholarvspubmed, fig.show = extraFigs, fig.cap = 'Logged number of references on scholar and pubmed, with a fitted (unphylogenetic) linear model. Colours indicate family.'
# Check how correlated pubmed and scholar are.
compSubspecies <- comparative.data(data = nSpecies, phy = pruneTree, names.col = 'binomial')
citeCor <- pgls(log(scholarRefs) ~ log(pubmedRefs + 1), data = compSubspecies, lambda = 'ML')
studyEffortCor <- summary(citeCor)
# And plot
ggplot(nSpecies, aes(x = scholarRefs, y = pubmedRefs + 1)) +
geom_point(aes(colour = familyPlotCol), size = 2.5) +
geom_smooth(method = 'lm') +
scale_x_log10() +
scale_y_log10() +
scale_colour_hc()
%%end.rcode
%%begin.rcode subsDataCapts
subsDataCapts <- c(
'Unlogged number of virus species against log mass with a non-phylogenetic linear model added. Points are significantly jittered to try and reveal the severe overplotting in the bottom left corner in particular.',
'Number of virus species against logged number of subspecies (not marginal) with a non-phylogenetic linear model added. Points are significantly jittered to try and reveal the severe overplotting in the bottom left corner in particular.',
'Number of virus species against logged number of subspecies (not marginal) with a non-phylogenetic linear model added.',
'Virus species against study effort (log pubmed references +1)')
%%end.rcode
%%begin.rcode subsDataviz, fig.show = extraFigs, fig.cap = subsDataCapts
# A number of exploratory plots
# Mass against viruses
ggplot(nSpecies, aes(log(mass), virusSpecies)) +
geom_point(aes(colour = familyPlotCol), size = 2.5) +
geom_smooth(method = 'lm')+
labs(colour = 'Family') +
scale_colour_hc()
# N Subspecies and against viruses
ggplot(nSpecies, aes(NumberOfSubspecies, virusSpecies)) +
geom_jitter(aes(colour = familyPlotCol), size = 2.5,
position = position_jitter(width = .3, height = .3)) +
geom_smooth(method = 'lm')+
labs(colour = 'Family') +
scale_colour_hc()
# Log(N Subspecies) and against viruses
ggplot(nSpecies, aes(NumberOfSubspecies, virusSpecies)) +
geom_jitter(aes(colour = familyPlotCol), size = 2.5,
position = position_jitter(width = .05, height = .2)) +
scale_x_log10() +
geom_smooth(method = 'lm')+
labs(colour = 'Family') +
scale_colour_hc()
# N. Subspecies against viruses as a boxplot to deal with overplotting.
ggplot(nSpecies, aes(SubspeciesFactor, virusSpecies)) +
geom_boxplot() +
scale_x_discrete(limits = levels(nSpecies$SubspeciesFactor), drop=FALSE) +
geom_smooth(method = 'lm', aes(group = 1)) +
xlab('# subspecies')
# Study effort against virusSpecies
ggplot(nSpecies, aes(log(pubmedRefs + 1), virusSpecies)) +
geom_jitter(aes(colour = familyPlotCol), size = 2.5,
position = position_jitter(width = .1, height = .1)) +
geom_smooth(method = 'lm') +
labs(colour = 'Family')+
scale_colour_hc()
# Distribution size aginst virus
ggplot(nSpecies, aes(distrSize, virusSpecies)) +
geom_point(aes(colour = familyPlotCol), size = 2.5) +
geom_smooth(method = 'lm') +
labs(colour = 'Family') +
scale_colour_hc() +
scale_x_log10()
# Correlation plot
nSpecies %>%
dplyr::select(virusSpecies, NumberOfSubspecies, mass, distrSize, pubmedRefs, scholarRefs) %>%
mutate(mass = log(mass), distrSize = log(distrSize), pubmedRefs = log(pubmedRefs + 1), scholarRefs = log(scholarRefs)) %>%
ggpairs(.)
%%end.rcode
%%begin.rcode, subsAnalysis, fig.show = extraFigs
##################################################################################
## N Virus ~ subs + log(cites + mass)
subspeciesJointUnlog <- pgls(
virusSpecies ~ log(scholarRefs) + NumberOfSubspecies + log(mass),
data = compSubspecies, lambda = 'ML')
## N Virus ~ subs + log(cites + mass) + subs*log(cites)
subspeciesInter <- pgls(
virusSpecies ~ log(mass) +
NumberOfSubspecies*log(scholarRefs),
data = compSubspecies, lambda = 'ML')
#subInter.summary <- summary(subspeciesInter)
## Look at Variance inflation factors.
## Couple of help messages imply lm vif is fine.
#sqrt(vif(lm(virusSpecies ~ log(scholarRefs) + NumberOfSubspecies + log(mass) + log(distrSize), data = nSpecies)))
%%end.rcode
%%begin.rcode ITanalysis
varList <- c('scholarRefs', 'NumberOfSubspecies', 'mass', 'distrSize', 'rand')
findCombs <- function(k, vars, longest){
x <- t(combn(vars, k))
nas <- matrix(NA, ncol = longest - NCOL(x), nrow = nrow(x))
mat <- cbind(x, nas)
return(mat)
}
modelList <- lapply(0:5, function(k) findCombs(k, varList, 6))
modelMat <- do.call(rbind, modelList)
interMat <- modelMat[apply(modelMat, 1, function(x) "scholarRefs" %in% x & "NumberOfSubspecies" %in% x), ]
interMat[, 2:5] <- interMat[, 1:4]
interMat[, 1] <- "scholarRefs:NumberOfSubspecies"
allModelMat <- rbind(modelMat, interMat)
allFormulae <- apply(allModelMat[-1, ], 1, function(x) as.formula(paste('virusSpecies ~', paste(x[!is.na(x)], collapse = ' + '))))
allFormulae <- c(as.formula('virusSpecies ~ 1'), allFormulae)
modelSelect <- function(allForm, data, phy, boot, allModelMat, varList){
set.seed(paste0('123', boot))
bootData <- cbind(data, rand = runif(nrow(data)))
# log some predictors
bootData[, c('mass', 'scholarRefs', 'distrSize')] <- log(bootData[, c('mass', 'scholarRefs', 'distrSize')])
# scale
bootData[, c('mass', 'scholarRefs', 'distrSize', 'rand', 'NumberOfSubspecies')] <- base::scale(bootData[, c('mass', 'scholarRefs', 'distrSize', 'rand', 'NumberOfSubspecies')])
coefs <- matrix(NA, ncol = length(varList) + 2, nrow = nrow(allModelMat),
dimnames = list(NULL, paste0('beta.', c('(Intercept)', varList, 'scholarRefs:NumberOfSubspecies'))))
results <- apply(allModelMat, 1, function(x) sapply(c(varList, "scholarRefs:NumberOfSubspecies"), function(y) y %in% x)) %>%
t %>%
data.frame %>%
cbind(AIC = NA, boot = boot, lambda = NA, attempt = NA, predictors = NA, coefs)
# Fit each model
# I'm having problems with convergence so sometimes have to try different starting values.
for(m in 1:length(allForm)){
if(exists('model')){
rm(model)
}
try({
model <- gls(allForm[[m]], correlation = corPagel(value = 0.4, phy = phy), data = bootData, method = 'ML')
results$attempt[m] <- 1
})
if(!exists('model')){
try({
model <- gls(allForm[[m]], correlation = corPagel(value = 0.3, phy = phy), data = bootData, method = 'ML')
results$attempt[m] <- 2
})
}
if(!exists('model')){
try({
model <- gls(allForm[[m]], correlation = corPagel(value = 0.2, phy = phy), data = bootData, method = 'ML')