-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoolkit.R
1785 lines (1613 loc) · 76.4 KB
/
toolkit.R
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
# Trait dataset paper tool kit
# Created by P. Pata
# Last modified April 13, 2023
#
# ***** Trait dataset tool kit *****
#
# This file contains a set of functions that were utilized in developing and
# curating the zooplankton trait dataset. A list of the functions with short
# descriptions are reported below.
#
# ** Data curation functions **
#
# pooled.sd(SDarray, Narray): Calculates the pooled SD from two SDs. This is
# similar to the weighted mean. Note that this will only work if both arrays
# have N > 1.
# getSpeciesMeanSD(traitValue, dispersionSD, individualCount): Calculate the
# weighted means and SDs of traits when the dataset is a mix of individual
# values and averaged records.
# geomean(x): Calculates the geometric mean of an array.
# scaleFun(x): Returns a number with two decimal places.
# convertRateT2WS(df, sizeAssoc, trtName1, trtName2, trtUnit):
# Converts a by individual rate to a weight-specific rate.
# convertPW2Total(df, sizeAssoc, trtName1, trtName2, trtUnit = "mg"):
# Converts percent composition value to total bulk composition value.
# convertTotal2PW(df, sizeAssoc, trtName1, trtName2, trtUnit = "percent"):
# Converts total bulk composition to percent composition relative to a weight.
# mergeTraitDetails(df, trait.directory): Combine duplicated trait records of
# the same value but from different references.
# summarise.sizeAssoc(df): Calculates the average associated size of each trait
# and taxon pair in the df. This returns a sizeAssoc data frame with the mean
# N, and sd values which would be merged into the main df.
# updateIDs(data, trait.directory): Updates the trait and taxon-trait IDs.
# standardizeTable(file.list, s.format, taxonomy, lifestagelist, trait.directory):
# Reorders the column and converts the names and formats of the traits.
# annotateLifeStage(data, lifestagelist): Modifies how the life stage was coded,
# assigns the life stage ID, and records the original life stage.
# annotateTaxonomy(data, taxonomy): Assigns the taxonomic ID and the taxonomic
# ranks it belongs to. The recorded scientific name would be stored in the
# column verbatimScientificName.
# adjustClass(data, s.format): Changes the data class for numerical columns into
# character variables to facilitate merging of data frames into a single file.
# cleanStrings(A): Cleans spaces, NAs, and blanks from strings for notes and
# references. Also removes duplicated strings separated by ;.
# cleanStringsList(A): Apply cleanStrings() to a list.
# standard_temp(rate0, t0, t, Q10): Calculate the value of a rate to a reference
# temperature using a Q10 coefficient.
# cleanScientificName(name): Cleans the verbatim scientific name from trailing
# spaces and life stage information. Also removes the sp, aff, and cf texts.
# assignMajorGroup(taxonomy): Assigns the zooplankton major group in a taxonomy
# data frame.
# getMaxObsNum(traitName, taxonID, df): Gets the maximum observation number for
# a trait and species.
#
#
# ** Data imputation functions **
#
# getGroupLevelValue(taxon, trait, gen.level, trait.df, taxonomy.df)): Calculates
# the group-level mean, standard deviation, and number of species-level
# observations for generalization of a given trait for a taxon.
#
# conv.allom(W,a,b,base): General equation for allometric conversions.
# The default base is the natural log.
# getpval(x) : Calculates a p value from a regression model F statistic object.
#
# getRegressionModel(df, grp, X, Y, model): Derives the regression model between
# two trait variables for a zooplankton group.
# calculateFromModel(df, model, excludeWithLit, applyToGeneralized,
# excludeCalculated): Calculates a trait using a regression model.
# plotAllometric(df, grp, X, Y): Plots the distribution of values between two
# traits and a regression line. [!!! Should be sensitive to if OLS or RMA regressions.]
# plotRegModel(model): Plots a simple regression model result with 95% confidence
# intervals.
# calculate.WSRates(trait.df, traits.calculated, trait.X, trait.Y): Calculates
# the weight specific rate for traits with calculate rate values derived
# from regression equations.
#
# *** Functions for trait correlations ***
#
# calc_p_value(x, y): Calculates the p.value from either a t.test or the c
# or.test functions. Need to manually switch
# get_pairwise.N(x,y): Calculates the number of pair of two variables with data.
# widen_traits(trait.table, trait.list): Subsets the trait dataset to only
# the traits specified in the list. Only retains taxon information.
# correlate_traits(trait.table, trait.list): Calculates correlations between
# variables in trait.list and returns a long data frame of the correlation,
# N data pairs, and p-value.
# corphylo.tests(trait.num.phylo, trait.list, phylo.tree, zoop_vcv) :
# This runs different correlation tests using the phyr::cor_phylo() function.
# Note that this temporarily requires the phylo.tree and vcv objects to
# explore the effect of which phylo signal to use. This returns a long table
# or correlation results.
require(dplyr)
require(lmodel2)
require(lubridate)
require(corrr)
# Helper functions ----
`%notin%` <- Negate(`%in%`)
scaleFUN <- function(x) sprintf("%.2f", x)
geomean <- function(x) { exp(mean(log(x), na.rm = TRUE)) }
# Transformations for proportional or percent data.
# According to http://strata.uga.edu/8370/rtips/proportions.html. Logit is
# preferred for regressions because range is (-inf, inf), while arcsine is
# preferred for ordination and clustering because range is [0, 1] which
# works for multivariate methods. Both are linear at 0.3-0.7 range, logit
# gives a stronger transformation at the ends.
# arcsine transformation
asinTransform <- function(x) {
# if percent data, change to proportion
if (max(x) > 1 & min(x) >= 0 & max(x) <= 100) {
x <- x/100
} else if(min(x) < 0 | max(x) > 100){
stop("Error: Data must either be proportion [0,1] or percentage [0, 100]")
}
asin(sqrt(x))
}
# logit transformation
logitTransform <- function(x) {
# if percent data, change to proportion
if (max(x) > 1 & min(x) >= 0 & max(x) <= 100) {
x <- x/100
} else if(min(x) <= 0 | max(x) > 100){
stop("Error: Data must either be proportion [0,1] or percentage [0, 100]")
}
log(x/(1-x))
}
# pooled sd
pooled.sd <- function(SDarray, Narray){
sqrt(sum((Narray-1)*(SDarray)^2) / (sum(Narray) - length(Narray)) )
# # if inputs are: x,y,Nx,Ny
# sqrt( ((Nx-1)*x^2 + (Ny-1)*y^2) / (Nx+Ny-2))
}
# Data curation functions ----
# Calculate the weighted means and SDs of traits when the dataset is a mix of
# individual values and averaged records.
getSpeciesMeanSD <- function(traitValue, dispersionSD, individualCount){
# extract indiv values and grouped values
val.indiv <- traitValue[which(individualCount == 1)]
val.group.mean <- traitValue[which(individualCount > 1)]
val.group.N <- individualCount[which(individualCount > 1)]
val.group.sd <- dispersionSD[which(individualCount > 1)]
# calculate mean of the individual values
val.indiv.mean <- mean(val.indiv)
val.indiv.N <- length(val.indiv)
val.indiv.sd <- sd(val.indiv, na.rm = TRUE)
# calculate N
N <- sum(individualCount)
# calculate weighted mean
mean <- weighted.mean(c(val.indiv.mean, val.group.mean),
c(val.indiv.N, val.group.N))
# calculate pooled sd
# catch if val.indiv.N = 1, calculate the pooled sd from the groups vars only,
# note that the mean and N are of all though. This is obviously not accurate
# but would be a better estimate compared to calculating the unweighted sd,
# especially when the group.N sums to a large sample.
if (val.indiv.N == 1) {
sd <- pooled.sd(c(val.group.sd),
c(val.group.N))
} else {
sd <- pooled.sd(c(val.indiv.sd, val.group.sd),
c(val.indiv.N, val.group.N))
}
# calculate standard error
se <- sd / sqrt(N)
return(list("N" = N, "mean" = mean, "sd" = sd, "se" = se))
}
# for converting individual rates to weight specific
convertRateInd2WS <- function(df, sizeAssoc, trtName1, trtName2, trtUnit) {
D.1 <- df %>%
filter(traitName == trtName1)
D.2 <- df %>%
filter(traitName == trtName2) %>%
filter(taxonID %notin% D.1$taxonID) %>%
# Derived columns are the original columns
mutate(verbatimScientificName = scientificName,
verbatimTraitName = traitName,
verbatimTraitValue = as.character(traitValue),
verbatimTraitUnit = traitUnit,
verbatimLifeStage = lifeStage,
verbatimNotes = notes,
aggregateMeasure = FALSE,
isDerived = TRUE,
catalogSource = catalogNumber) %>%
select(-starts_with("sizeAssoc")) %>%
left_join(sizeAssoc, by = "taxonID") %>%
filter(!is.na(sizeAssocValue)) %>%
group_by(traitID, taxonID) %>%
mutate(traitName = trtName1,
traitValue = traitValue/sizeAssocValue,
traitUnit = trtUnit,
basisOfRecord = "derived from related trait",
dispersionSD = NaN,
individualCount = 1,
notes = paste0("Calculated from ",trtName1," and ",
trtName2,"; based on", catalogNumber),
isDerived = TRUE,
maxObsNum = 0) %>%
ungroup() %>%
standardizeID(trait.directory)
}
# for converting weight specific rates to individual-specific
convertRateWS2Ind <- function(df, sizeAssoc, trtName1, trtName2, trtUnit) {
D.1 <- df %>%
filter(traitName == trtName1)
D.2 <- df %>%
filter(traitName == trtName2) %>%
filter(taxonID %notin% D.1$taxonID) %>%
# Derived columns are the original columns
mutate(verbatimScientificName = scientificName,
verbatimTraitName = traitName,
verbatimTraitValue = as.character(traitValue),
verbatimTraitUnit = traitUnit,
verbatimLifeStage = lifeStage,
verbatimNotes = notes,
aggregateMeasure = FALSE,
isDerived = TRUE,
catalogSource = catalogNumber) %>%
select(-starts_with("sizeAssoc")) %>%
left_join(sizeAssoc, by = "taxonID") %>%
filter(!is.na(sizeAssocValue)) %>%
group_by(traitID, taxonID) %>%
mutate(traitName = trtName1,
traitValue = traitValue*sizeAssocValue,
traitUnit = trtUnit,
basisOfRecord = "derived from related trait",
dispersionSD = NaN,
individualCount = 1,
notes = paste0("Calculated from ",trtName1," and ",
trtName2,"; based on", catalogNumber),
isDerived = TRUE,
maxObsNum = 0) %>%
ungroup() %>%
standardizeID(trait.directory)
}
# for converting between bulk and percent composition
convertPW2Total <- function(df, sizeAssoc, trtName1, trtName2, trtUnit = "mg"){
D.1 <- df %>%
filter(traitName == trtName1)
D.2 <- df %>%
filter(traitName == trtName2) %>%
filter(taxonID %notin% D.1$taxonID) %>%
# Derived columns are the original columns
mutate(verbatimScientificName = scientificName,
verbatimTraitName = traitName,
verbatimTraitValue = as.character(traitValue),
verbatimTraitUnit = traitUnit,
verbatimLifeStage = lifeStage,
verbatimNotes = notes,
aggregateMeasure = FALSE,
isDerived = TRUE,
catalogSource = catalogNumber) %>%
select(-starts_with("sizeAssoc")) %>%
left_join(sizeAssoc, by = "taxonID") %>%
filter(!is.na(sizeAssocValue)) %>%
group_by(traitID, taxonID) %>%
mutate(traitName = trtName1,
traitValue = traitValue*sizeAssocValue / 100,
traitUnit = trtUnit,
basisOfRecord = "derived from related trait",
dispersionSD = NaN,
individualCount = 1,
notes = paste0("Calculated from ",trtName1," and ",
trtName2,"; based on", catalogNumber),
isDerived = TRUE,
maxObsNum = 0) %>%
ungroup() %>%
standardizeID(trait.directory)
# updateIDs(trait.directory)
}
convertTotal2PW <- function(df, sizeAssoc, trtName1, trtName2, trtUnit = "percent") {
D.1 <- df %>%
filter(traitName == trtName1)
D.2 <- df %>%
filter(traitName == trtName2) %>%
filter(taxonID %notin% D.1$taxonID) %>%
# Derived columns are the original columns
mutate(verbatimScientificName = scientificName,
verbatimTraitName = traitName,
verbatimTraitValue = as.character(traitValue),
verbatimTraitUnit = traitUnit,
verbatimLifeStage = lifeStage,
verbatimNotes = notes,
aggregateMeasure = FALSE,
isDerived = TRUE,
catalogSource = catalogNumber) %>%
select(-starts_with("sizeAssoc")) %>%
left_join(sizeAssoc, by = "taxonID") %>%
filter(!is.na(sizeAssocValue)) %>%
group_by(traitID, taxonID) %>%
mutate(traitName = trtName1,
traitValue = traitValue/sizeAssocValue * 100,
traitUnit = trtUnit,
basisOfRecord = "derived from related trait",
dispersionSD = NaN,
individualCount = 1,
isDerived = TRUE,
notes = paste0("Calculated from ",trtName1," and ",
trtName2,"; based on", catalogNumber),
maxObsNum = 0) %>%
ungroup() %>%
# updateIDs(trait.directory) %>%
standardizeID(trait.directory) %>%
filter(traitValue <= 100)
}
calculateRatio <- function(df, ratio, trtName1, trtName2){
D.0 <- df %>%
filter(traitName == ratio)
D.1 <- df %>%
filter(traitName == trtName1) %>%
filter(taxonID %notin% D.0$taxonID) %>%
select(catalogNumber, taxonID, traitValue1 = traitValue, scientificName,
taxonRank, acceptedNameUsageID, acceptedNameUsage, kingdom, phylum,
class, order, family, genus, majorgroup)
D.2 <- df %>%
filter(traitName == trtName2) %>%
filter(taxonID %notin% D.0$taxonID) %>%
select(catalogNumber, taxonID, traitValue2 = traitValue)
D.3 <- inner_join(D.1, D.2, by = "taxonID") %>%
mutate(traitValue = traitValue1/traitValue2, traitName = ratio,
traitUnit = NA,
valueType = "numeric",
basisOfRecord = "derived from related trait",
notes = paste0("Calculated from ",trtName1," and ",
trtName2),
catalogSource = paste0(catalogNumber.x, "; ", catalogNumber.y),
isDerived = TRUE,
observationNumber = 1, maxObsNum = 1, traitID = NA) %>%
# Above is ratio by weight so convert to molar ratio
mutate(traitValue = if_else(traitName == "ratioCN",
traitValue * (14.0067/12.011), traitValue)) %>%
mutate(traitValue = if_else(traitName == "ratioCP",
traitValue * (30.97376/12.011), traitValue)) %>%
mutate(traitValue = if_else(traitName == "ratioNP",
traitValue * (30.97376/14.0067), traitValue)) %>%
# exclude values outside the range of observed values
filter(traitValue >= min(D.0$traitValue) & traitValue <= max(D.0$traitValue)) %>%
select(-c(catalogNumber.x, catalogNumber.y, traitValue1, traitValue2)) %>%
standardizeID(trait.directory)
}
# For merging duplicated trait values or taxa-level averages. Note that this should be called for a grouped dataframe.
mergeTraitDetails <- function(df, trait.directory, rev.by = "P. Pata") {
df <- df %>%
mutate(dup = n())
df.same <- df %>%
filter(dup == 1) %>%
mutate(aggregateMeasure = FALSE) %>%
ungroup()
df.updated <- df %>%
filter(dup > 1) %>%
mutate(aggregateMeasure = TRUE) %>%
mutate(primaryReference = paste(primaryReference, collapse = "; "),
primaryReferenceDOI = paste(primaryReferenceDOI, collapse = "; "),
secondaryReference = paste(secondaryReference, collapse = "; "),
secondaryReferenceDOI = paste(secondaryReferenceDOI, collapse = "; "),
lifeStage = paste(lifeStage, collapse = "; "),
sizeType = paste(sizeType, collapse = "; "),
# sizeAssocName = paste(sizeAssocName, collapse = "; "),
# sizeAssocUnit = paste(sizeAssocUnit, collapse = "; "),
# sizeAssocValue = paste(sizeAssocValue, collapse = "; "),
# sizeAssocReference = paste(sizeAssocReference, collapse = "; "),
verbatimLocality = paste(verbatimLocality, collapse = "; "),
# decimalLongitude = paste(decimalLongitude, collapse = "; "),
# decimalLatitude = paste(decimalLatitude, collapse = "; "),
notes = paste(notes, collapse = "; "),
basisOfRecord = paste(basisOfRecord, collapse = "; "),
basisOfRecordDescription = paste(basisOfRecordDescription, collapse = "; "),
# Updated March 22, 2023: Now the verbatim records are not retained
# when merging rows. Instead the data can be extracted from the
# catalogSource.
verbatimScientificName = NA, verbatimTraitName = NA,
verbatimTraitValue = NA, verbatimTraitUnit = NA,
verbatimLifeStage = NA, verbatimTemperature = NA,
verbatimNotes = NA,
# verbatimScientificName = paste(verbatimScientificName, collapse = "; "),
# verbatimTraitName = paste(verbatimTraitName, collapse = "; "),
# verbatimTraitValue = paste(verbatimTraitValue),
# verbatimTraitUnit = paste(verbatimTraitUnit, collapse = "; "),
# verbatimLifeStage = paste(verbatimLifeStage, collapse = "; "),
# verbatimNotes = paste(verbatimNotes, collapse = "; "),
catalogSource = paste(catalogNumber, collapse = "; ") ) %>%
# clean strings
mutate(primaryReference = cleanStrings(primaryReference),
primaryReferenceDOI = cleanStrings(primaryReferenceDOI),
secondaryReference = cleanStrings(secondaryReference),
secondaryReferenceDOI = cleanStrings(secondaryReferenceDOI),
lifeStage = cleanStrings(lifeStage),
sizeType = cleanStrings(sizeType),
# sizeAssocName = cleanStrings(sizeAssocName),
# sizeAssocUnit = cleanStrings(sizeAssocUnit),
# sizeAssocValue = cleanStrings(sizeAssocValue),
# sizeAssocReference = cleanStrings(sizeAssocReference),
verbatimLocality = cleanStrings(verbatimLocality),
# decimalLongitude = cleanStrings(decimalLongitude),
# decimalLatitude = cleanStrings(decimalLatitude),
notes = cleanStrings(notes),
basisOfRecord = cleanStrings(basisOfRecord),
basisOfRecordDescription = cleanStrings(basisOfRecordDescription),
# verbatimScientificName = cleanStrings(verbatimScientificName),
# verbatimTraitName = cleanStrings(verbatimTraitName),
# verbatimTraitValue = cleanStrings(verbatimTraitValue),
# verbatimTraitUnit = cleanStrings(verbatimTraitUnit),
# verbatimLifeStage = cleanStrings(verbatimLifeStage),
# verbatimNotes = cleanStrings(verbatimNotes),
catalogSource = cleanStrings(catalogNumber) )%>%
distinct(catalogSource, .keep_all = TRUE) %>%
# mutate(observationNumber = NA) %>%
# updateIDs() %>%
mutate(notes = cleanStrings(paste("Trait value merged from multiple records.; ", notes))) %>%
# update upload date
mutate(uploadBy = rev.by, uploadDate = as.character(ymd(Sys.Date()))) %>%
ungroup()
df <- bind_rows(df.same, df.updated) %>%
select(-dup)
}
# This function removes the values in the verbatim columns when processing
# level 2 or 3 data such as merging multiple records or deriving the mean.
# As a fail-safe, this only deletes the verbatim records when the value for
# catalogSource is not empty, i.e., the record was based on something else.
removeVerbatimRecords <- function(df) {
# Preserve the order of rows
df <- df %>%
rownames_to_column(var = "rowIndex")
# Separate into if merged/derived or not
df.A <- df %>%
filter(is.na(catalogSource))
df.B <- df %>%
filter(!is.na(catalogSource)) %>%
mutate(verbatimScientificName = NA, verbatimTraitName = NA,
verbatimTraitValue = NA, verbatimTraitUnit = NA,
verbatimLifeStage = NA, verbatimTemperature = NA,
verbatimNotes = NA)
# merge back and rearrange rows
df <- bind_rows(df.A, df.B) %>%
arrange(rowIndex) %>%
select(-rowIndex)
return(df)
}
# Function for selecting the average associated size for a trait value. If there
# are multiple size types for a trait, the one with the highest sample size
# will be selected. References will also be summarized. Note that this may be
# a useful reference but it does not correspond to the species-average size
# value. For analyses requiring comparing the trait with size, it might be
# better to use the species-averaged size instead of the averaged sizeAssocValue.
summarise.sizeAssoc <- function(df) {
A <- df %>%
select(traitID, taxonID,
sizeAssocName, sizeAssocValue, sizeAssocUnit, sizeAssocReference) %>%
filter(!is.na(sizeAssocValue)) %>%
group_by(traitID, taxonID, sizeAssocName, sizeAssocUnit) %>%
# mutate(N = n(),
# Nmax = max(N)) %>%
# ungroup() %>%
# filter(N == Nmax) %>%
# group_by(traitID, taxonID, traitUnit) %>%
mutate(sizeAssocN = n(),
sizeAssocSD = sd(sizeAssocValue, na.rm = TRUE),
sizeAssocValue = mean(sizeAssocValue, na.rm = TRUE),
sizeAssocReference = cleanStrings(paste(sizeAssocReference,
collapse = "; "))) %>%
ungroup() %>%
distinct(traitID, taxonID,
sizeAssocName, sizeAssocValue, sizeAssocUnit, sizeAssocReference,
sizeAssocN, sizeAssocSD) %>%
# arrange and get first instance
group_by(traitID, taxonID) %>%
arrange(sizeAssocN) %>%
filter(row_number() == 1)
}
# Update the trait ID and unit when standardizing raw data
standardizeID <- function(data, trait.directory){
col.order <- colnames(data)
data <- data %>%
select(-c(traitID)) %>%
left_join(distinct(trait.directory, traitID, traitName), by = "traitName") %>%
relocate(col.order)
}
standardizeUnit <- function(data, trait.directory){
col.order <- colnames(data)
data <- data %>%
select(-c(traitUnit)) %>%
left_join(distinct(trait.directory, traitName, traitUnit), by = "traitName") %>%
relocate(col.order)
}
# For updating trait IDs and taxon-trait-IDs
# master.ID.List is a dataframe that keep tracks of the maximum observation
# of each traitID and taxonID. Need to regenerate this df after every time
# updateIDs is called
updateIDs <- function(data) {
# Create and update a masterIDList file which is loaded and updated by this function.
# This would be a safer approach when records are curated so a trait and species
# may completely be excluded and thus the maxObsNum resets to 0.
load("data_input/master_id_list.RData")
col.order <- colnames(data)
data <- data %>%
select(-maxObsNum) %>%
left_join(master.ID.List, by = c("traitID", "taxonID")) %>%
group_by(traitID,taxonID) %>%
# if there is no maxObsNum set to zero
mutate(maxObsNum = if_else(is.na(maxObsNum), 0, maxObsNum)) %>%
# if there is no observation number, assign one
mutate(observationNumber = if_else(!is.na(observationNumber),
observationNumber,
maxObsNum + row_number())) %>%
# update the maxObsNum to either be the original value or the max updated
# observation number.
mutate(maxObsNum = max(c(observationNumber, maxObsNum))) %>%
# if there is no catalogNumber, assign one
mutate(catalogNumber = if_else(is.na(catalogNumber),
paste0(traitID,"-",taxonID,"-",observationNumber),
catalogNumber)) %>%
ungroup() %>%
relocate(col.order)
# Update the list of maxObsNum
# master.ID.List <- master.ID.List %>%
master.ID.List <- master.ID.List %>%
bind_rows(distinct(data, traitID, taxonID, maxObsNum)) %>%
group_by(traitID, taxonID) %>%
summarise(maxObsNum = max(maxObsNum), .groups = "drop")
save(master.ID.List, file = "data_input/master_id_list.RData")
# print(paste0("Updated master ID list. N rows = ", nrow(master.ID.List),
# " N maxObsNum = ", length(unique(master.ID.List$maxObsNum))))
return(data)
}
# Functions for standardizing trait files
standardizeTable <- function(file.list, s.format, taxonomy, lifestagelist,
trait.directory, rev.by = "P. Pata") {
data <- s.format
# # These columns are set during database curation
# dplyr::select(-c(catalogSource, maxObsNum, aggregateMeasure))
for(i in file.list) {
d <- openxlsx::read.xlsx(paste0(infol,i)) %>%
mutate(secondaryReference = as.character(secondaryReference))
if("traitUnit" %notin% colnames(d)){
d <- d %>%
mutate(traitUnit = NA)
}
if("verbatimTraitUnit" %notin% colnames(d)){
d <- d %>%
mutate(verbatimTraitUnit = NA)
}
d <- d %>%
mutate(traitValue = as.character(traitValue),
verbatimTraitValue = as.character(verbatimTraitValue)) %>%
# set traitID, traitName based on trait directory
select(-c(traitName, traitUnit)) %>%
left_join(select(trait.directory, traitID, traitName,
verbatimTraitName, verbatimTraitUnit),
by = c("verbatimTraitName","verbatimTraitUnit"))
if("individualCount" %in% colnames(d)) {
d$individualCount <- as.numeric(str_trim(d$individualCount))
}
if("assocTemperature" %in% colnames(d)) {
d$assocTemperature <- as.character(d$assocTemperature)
d$verbatimTemperature <- as.character(d$assocTemperature)
}
if("lifeStage" %in% colnames(d)) {
d$lifeStage <- as.character(d$lifeStage)
}
if("verbatimLocality" %in% colnames(d)) {
d$verbatimLocality <- as.character(d$verbatimLocality)
}
if("notes" %in% colnames(d)) {
d$notes <- as.character(d$notes)
}
# Update some fields to match DWC (March 16, 2023)
if("longitude" %in% colnames(d)) {
d <- d %>%
rename(decimalLongitude = longitude)
}
if("latitude" %in% colnames(d)) {
d <- d %>%
rename(decimalLatitude = latitude)
}
if("rank" %in% colnames(d)){
d <- d %>%
rename(taxonRank = rank)
}
data <- data %>%
bind_rows(d)
}
# Filter duplicates (Updated Feb 11 2023)
data <- data %>%
distinct(verbatimScientificName, verbatimTraitName, verbatimTraitUnit,
verbatimTraitValue, lifeStage,
primaryReference, secondaryReference,
assocTemperature, .keep_all = TRUE)
# Annotate taxonomy information
data <- annotateTaxonomy(data, taxonomy) %>%
# Set stage ID
annotateLifeStage(lifestagelist) %>%
# Record file generation time stamp
mutate(uploadBy = rev.by, uploadDate = ymd(Sys.Date())) %>%
# Remove not in mesozooplankton major groups of interest
filter(!is.na(majorgroup)) %>%
# assign catalogNumber
group_by(traitID,taxonID) %>%
mutate(observationNumber = row_number()) %>%
mutate(catalogNumber = paste0(traitID,"-",taxonID,"-",observationNumber)) %>%
mutate(maxObsNum = max(observationNumber)) %>%
ungroup() %>%
# trait unit = verbatim trait unit if empty
mutate(traitUnit = if_else(is.na(traitUnit), verbatimTraitUnit, traitUnit)) %>%
# assign trait value source
mutate(basisOfRecord = "literature") %>%
relocate(colnames(s.format))
}
annotateLifeStage <- function(data, lifestagelist) {
data <- data %>%
mutate(verbatimLifeStage = lifeStage) %>%
select(-c(lifeStage, stageID)) %>%
left_join(lifestagelist, by = "verbatimLifeStage")
}
annotateTaxonomy <- function(data, taxonomy) {
data <- data %>%
select(-c(taxonID, scientificName, acceptedNameUsageID, acceptedNameUsage,
taxonRank, kingdom, phylum, class, order, family, genus,
majorgroup)) %>%
mutate(vsn_ed = cleanScientificName(verbatimScientificName)) %>%
left_join(select(taxonomy, verbatimScientificName, scientificName,
taxonID, acceptedNameUsageID,
acceptedNameUsage,
taxonRank, kingdom, phylum, class, order, family, genus,
majorgroup),
by = c("vsn_ed" = "verbatimScientificName")) %>%
select(-vsn_ed)
}
# Function for changing class types to merge separate level 1 data files.
# Need to improve this code to include all columns
adjustClass <- function(data, s.format){
data <- data %>%
mutate(traitUnit = as.character(traitUnit),
lifeStage = as.character(lifeStage),
assocTemperature = as.character(assocTemperature),
primaryReferenceDOI = as.character(primaryReferenceDOI),
secondaryReferenceDOI = as.character(secondaryReferenceDOI),
uploadDate = as.character(uploadDate),
sizeType = as.character(sizeType),
sizeAssocName = as.character(sizeAssocName),
sizeAssocUnit = as.character(sizeAssocUnit),
sizeAssocReference = as.character(sizeAssocReference),
verbatimLocality = as.character(verbatimLocality),
# species = as.character(species),
basisOfRecordDescription = as.character(basisOfRecordDescription),
verbatimTraitUnit = as.character(verbatimTraitUnit),
verbatimLifeStage = as.character(verbatimLifeStage),
verbatimTemperature = as.character(verbatimTemperature),
verbatimNotes = as.character(verbatimNotes),
catalogSource = as.character(catalogSource),
aggregateMeasure = as.logical(aggregateMeasure),
isDerived = as.logical(isDerived),
errorRisk = as.numeric(errorRisk),
errorRiskRank = as.character(errorRiskRank),
notes = as.character(notes))
# for (i in c(1:ncol(data))) {
# if(colnames(data[i]) == colnames(s.format[i])){
# if (class(s.format[,i]) == "character") {
# data[,i] <- as.character(data[,i])
# }
# if (class(s.format[,i]) == "numeric") {
# data[,i] <- as.numeric(data[,i])
# }
# }
# }
}
# function for cleaning concatenated strings
cleanStrings <- function(A){
A <- str_split(A, pattern =";", simplify = TRUE)
A <- str_trim(A)
A <- sort(A)
A <- str_replace(A, "NA", replacement = "")
A <- A[A != '']
A <- unique(as.list(A))
A <- paste(A, collapse = "; ")
A <- as.character(A)
}
cleanStringsList <- function(A){
A <- lapply(A, cleanStrings)
}
standard_temp <- function(rate0, t0, t = 15, Q10 = 2.8) {
10^(log10(rate0) + log10(Q10)*((t-t0)/10) )
}
cleanScientificName <- function(name){
# remove trailing *sp., ?-. symbols, and anything inside parenthesis
# remove trailing life stage information
name <- gsub(" aff\\.","", name)
name <- gsub(" cf\\.","", name)
name <- gsub(" C4| C5| CI| CIV| CV| III| IV| VI| NI| NII| NIII| NIV| NV","",name)
name <- str_replace(name, "\\s*\\([^\\)]+\\)", "")
name <- str_replace_all(name, "[[:punct:]]", "")
name <- str_replace_all(name, "[:digit:]", "")
name <- gsub(" sp$","", name)
name <- gsub(" spp$","", name)
name <- gsub(" V$","", name)
name <- str_replace(name, " female","")
name <- str_replace(name, " male","")
name <- str_replace(name, "Agg","")
name <- str_replace(name, "aggregate","")
name <- str_replace(name, "solitary","")
name <- str_squish(str_trim(name))
name
}
# Assign major group based on a row/s of taxonomy information
assignMajorGroup <- function(taxonomy){
taxonomy <- taxonomy %>%
mutate(majorgroup = "") %>%
mutate(majorgroup = if_else(class %in% c("Polychaeta"),"Polychaete",majorgroup)) %>%
mutate(majorgroup = if_else(phylum %in% c("Chaetognatha"),"Chaetognath",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Branchiopoda"),"Cladoceran",majorgroup)) %>%
mutate(majorgroup = if_else(phylum %in% c("Ctenophora"),"Ctenophore",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Scyphozoa"),"Scyphomedusae",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Siphonophorae"),"Siphonophore",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Narcomedusae","Leptothecata",
"Trachymedusae","Limnomedusae",
"Anthoathecata"),
"Hydromedusae",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Pteropoda"),"Pteropod",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Thaliacea"), "Thaliacean",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Appendicularia"),
"Appendicularian",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Ostracoda"), "Ostracod",majorgroup)) %>%
mutate(majorgroup = if_else(class %in% c("Copepoda"),"Non-calanoid",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Calanoida"),"Calanoid",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Amphipoda"),"Amphipod",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Decapoda"),"Decapod",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Euphausiacea"),"Euphausiid",majorgroup)) %>%
mutate(majorgroup = if_else(order %in% c("Mysida","Mysidacea"),
"Mysid",majorgroup))
return(taxonomy$majorgroup)
}
getMaxObsNum <- function(traitName, taxonID, df) {
df <- df %>%
filter(traitName == traitName & taxonID == taxonID)
if (nrow(df) > 0) {
i <- max(df$observationNumber)
} else {
i <- 0
}
i
}
# Data imputation functions ----
# This function calculates the mean, standard deviation, and number of
# observations for generalization of a given trait for a taxon. This will not
# generate an updated catalogNumber and this should created if including the
# generalized trait observation in the overall trait table.
getGroupLevelValue <- function(taxon, trait, gen.level = "genus", trait.df, taxonomy.df){
# check if trait is numeric or binary
trait.type <- trait.df %>%
filter(traitName == trait) %>%
filter(row_number()==1) %>%
select(valueType)
if (trait.type$valueType %notin% c("numeric","binary")) {
stop("Error: Please select a trait that is either numeric or binary.")
}
# get taxonomy details of a taxon
taxon.details <- taxonomy.df %>%
filter(scientificName == taxon) %>%
distinct(taxonID, .keep_all = TRUE)
if (nrow(taxon.details) == 0) {
stop("Error: Please select a scientific name that is found in the taxonomy data frame.")
}
# get a list of species that are in the focus taxon's group
if (gen.level == "genus"){
taxon.group <- taxonomy.df %>%
filter(genus == taxon.details$genus)
} else if (gen.level == "family") {
taxon.group <- taxonomy.df %>%
filter(family == taxon.details$family)
} else if (gen.level == "order") {
taxon.group <- taxonomy.df %>%
filter(order == taxon.details$order)
} else {
stop("Error: Please select a generalization level that is either genus, family, or order.")
}
taxon.group <- taxon.group %>%
filter(taxonRank %in% c("Species", "Subspecies")) %>%
distinct(taxonID, scientificName)
# filter the trait dataframe to select the trait and the species of interest
trait.sub <- trait.df %>%
filter(traitName == trait) %>%
filter(taxonID %in% taxon.group$taxonID)
# If there are no other taxa found for this species, return with a blank and provide a warning that there was no generalization.
if(nrow(trait.sub) == 0){
warning("Warning: There are no records of the selected trait at the selected group level.")
return(NA)
}
# Calculate the mean and standard deviation across all members in a group and return a row of generalized trait value following the standardized format.
generalized.trait <- trait.sub %>%
mutate(traitValue = as.numeric(traitValue)) %>%
mutate(dispersionSD = sd(traitValue, na.rm = TRUE), individualCount = n(),
traitValue = mean(traitValue),
basisOfRecord = "generalized",
notes = paste0("Trait value generalized from the ",gen.level," level average.")) %>%
distinct(traitID, traitName, traitValue, traitUnit, valueType,
assocTemperature, dispersionSD, individualCount,
notes, basisOfRecord) %>%
bind_cols(select(taxon.details, -c(verbatimScientificName)))
return(generalized.trait)
}
# general equation for allometric conversion, base defaults to natural log
conv.allom <- function(W,a,b,base = exp(1)) {
base^(a + (b*log(W,base)))
}
getpval <- function(x){
p <- pf(x[1],x[2],x[3],lower.tail = F)
attributes(p) <- NULL
return(p)
}
# This is a wrapper for an OLS regression and does not calculate confidence intervals.
getRegressionModel <- function(df, grp = "All", X, Y, base = "10") {
trait.sub <- df %>%
filter(traitName %in% c(all_of(X), all_of(Y)))
if (grp != "All") {
trait.sub <- trait.sub %>%
filter(str_detect(group, grp))
}
trait.sub <- trait.sub %>%
filter(taxonRank %in% c("Subspecies","Species")) %>%
select(taxonID, scientificName, traitName, traitValue, majorgroup) %>%
pivot_wider(names_from = traitName, values_from = traitValue) %>%
filter(!is.na(get(X)) & !is.na(get(Y))) %>%
relocate(X, Y)
if (nrow(trait.sub) > 3) {
# Calculate OLS
if(base == "10") {
reg <- lm(log10(get(Y)) ~ log10(get(X)), data = trait.sub)
} else if (base == "e") {
reg <- lm(log(get(Y)) ~ log(get(X)), data = trait.sub)
} else {
stop("Error: Please select either base 10 or e.")
}
reg.results.size <- data.frame(grp = grp, X = X, Y = Y,
a = reg$coefficients[1],
b = reg$coefficients[2],
n = nrow(trait.sub),
R2 = summary(reg)$adj.r.squared,
RSE = summary(reg)$sigma,
pval = getpval(summary(reg)$fstatistic),
model = "OLS", base = as.character(base),
minX = min(trait.sub[,1]), maxX = max(trait.sub[,1]))
} else {
reg.results.size <- data.frame(grp = grp, X = X, Y = Y,
a = NA, b = NA, n = nrow(trait.sub),
R2 = NA, RSE = NA, pval = NA,
model = "OLS", base = as.character(base),
minX = NA, maxX = NA)
}
}
# Calculates regression model using the lmodel2() function that allows major axis regressions
# df is a standardized trait dataframe
getRegressionModel2 <- function(df, grp = "All", X, Y,
model = "OLS", base = "10"){
trait.sub <- df %>%
filter(traitName %in% c(all_of(X), all_of(Y)))
if (grp != "All") {
trait.sub <- trait.sub %>%
filter(str_detect(group, grp))
}
trait.sub <- trait.sub %>%
filter(taxonRank %in% c("Subspecies","Species")) %>%
select(taxonID, scientificName, traitName, traitValue, majorgroup) %>%
pivot_wider(names_from = traitName, values_from = traitValue) %>%
filter(!is.na(get(X)) & !is.na(get(Y))) %>%
relocate(X, Y)
# This calculates both the OLS and RMA
if(base == "10") {
reg <- lmodel2(log10(get(Y)) ~ log10(get(X)), data = trait.sub)
} else if (base == "e") {
reg <- lmodel2(log(get(Y)) ~ log(get(X)), data = trait.sub)
} else {
stop("Error: Please select either base 10 or e.")
}
if (model == "OLS"){
ii <- 1
} else if (model =="RMA") {
ii <- 3
} else {
stop("Error: Please select either OLS or RMA regression model.")
}
# return(reg)
reg.results.size <- data.frame(grp = grp, X = X, Y = Y,
a = reg$regression.results$Intercept[ii],
b = reg$regression.results$Slope[ii],
a.ci.2.5 = reg$confidence.intervals$`2.5%-Intercept`[ii],
a.ci.97.5 = reg$confidence.intervals$`97.5%-Intercept`[ii],
b.ci.2.5 = reg$confidence.intervals$`2.5%-Slope`[ii],
b.ci.97.5 = reg$confidence.intervals$`97.5%-Slope`[ii],
n = nrow(trait.sub),
R2 = reg$rsquare,
# RSE = reg$sigma,
pval = reg$P.param,
model = model, base = as.character(base),
minX = min(trait.sub[,1]), maxX = max(trait.sub[,1]))
}
# calculate values based on an allometric conversion model
calculateFromModel <- function(df, model, trait.directory, excludeWithLit = TRUE,
applyToGeneralized = FALSE,
excludeCalculated = TRUE) {
# make sure this is just one model
stopifnot(nrow(model) == 1)
# error if the base of the logarithm is not 10 or e (natural log).
if (!(model$base == "10" | model$base == "e" | model$base == "ln")) {
stop("Error: Please select model with either base 10 or e.")
}
df.withdata <- df %>%
# filter(str_detect(basisOfRecord, "literature|calculated taxon average| midpoint")) %>%
filter(traitName %in% model$Y)
df.calc <- df %>%
# Assign the verbatim trait information as the calculated values
mutate(verbatimTraitName = traitName, verbatimTraitUnit = traitUnit,
verbatimTraitValue = as.character(traitValue), verbatimNotes = notes) %>%
select(-c(primaryReferenceDOI, secondaryReferenceDOI, catalogNumber,
sizeAssocName, sizeAssocUnit, sizeAssocValue,
sizeAssocN, sizeAssocSD, assocTemperature,
sizeAssocReference, verbatimLocality,
decimalLongitude, decimalLatitude, notes,
aggregateMeasure, isDerived, catalogSource, basisOfRecordDescription)) %>%
filter(str_detect(group, model$grp),