-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.R
1361 lines (1235 loc) · 48.2 KB
/
function.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
# These functions are needed to run the analyses of the Norwegian Red Lists
# for species described in the paper "Metrics for quantifying how much
# different threats contribute to red lists of species and ecosystems".
# Equations refer to the same paper.
# ========================
# Auxiliary functions
# ========================
# The following functions have nothing to do with Red Lists.
# I just used them to simplify some code, so they need to be defined first.
# Tests whether the arguments are equal. Robust against rounding errors!
"%=%" <- function(arg1, arg2) {
attributes(arg1) <- NULL
attributes(arg2) <- NULL
return(identical(all.equal(arg1, arg2), TRUE))
}
# Combines text strings
"%+%" <- function(string1, string2) paste0(string1, string2)
# Calculates the union of two sets (vectors)
"%A%" <- function(set1, set2)
if (is.null(set1)) logical(0) else as.vector(na.omit(set1[set1 %in% set2]))
# Removes an element of a set
"%-%" <- function(arg1, arg2) arg1[which(!(arg1 %in% na.omit(arg2)))]
# I just find this more intuitive...
"%contains%" <- function(vector, search) grepl(search, vector, fixed = TRUE)
# Decadal logarithm should be abbreviated "lg"!
lg <- function(x) log10(x)
# Logit function
logit <- function(x) log(x / (1 - x))
# Inverse of the logit function
invlogit <- function(x) ifelse(x > 100, 1, exp(x) / (1 + exp(x)))
# Ceiling function that keeps two decimals
c100 <- function(x) ceiling(x * 100) / 100
# Floor function that keeps two decimals
f100 <- function(x) floor(x * 100) / 100
# ========================
# RLI functions
# ========================
# Tests for data deficiency
isDD <- function(x) x %in% DD
# Tests whether a species/ecosystem is (near) threatened
isConcern <- function(x) x %in% (LC.EX %-% LC)
# Tests whether a species/ecosystem is extinct/collapsed
isExtinct <- function(x) x %in% extinct
# Extracts the threat factor from a text string
extractThreat <- function(x) return(
as.vector(unlist(as.data.frame(strsplit(x, ":"))[1, ]))
)
# Extracts the timing of a threat from a text string
extractTiming <- function(x) return(
as.vector(unlist(as.data.frame(strsplit(x, ":"))[2, ]))
)
# Extracts the scope of a threat from a text string
extractScope <- function(x) return(
as.vector(unlist(as.data.frame(strsplit(x, ":"))[3, ]))
)
# Extracts the severity of a threat from a text string
extractSeverity <- function(x) return(
as.vector(unlist(as.data.frame(strsplit(x, ":"))[4, ]))
)
RLW <- function(x, t = 0, method = weightingRLI) {
# Red List Weights
method <- tolower(method)
wt <- NULL
if (substr(method, 1, 2) == "eq") wt <- RLW.eqSteps(x, t)
if (method == "a1") wt <- RLW.A1 (x, t)
if (method == "a2") wt <- RLW.A2 (x, t)
if (method == "b") wt <- RLW.B1 (x, t)
if (method == "b1") wt <- RLW.B1 (x, t)
if (method == "b2") wt <- RLW.B2 (x, t)
if (method == "c") wt <- RLW.C (x, t)
if (method == "c1") wt <- RLW.C (x, t)
if (method == "d") wt <- RLW.D (x, t)
if (method == "d1") wt <- RLW.D (x, t)
if (method == "e") wt <- RLW.Ev1(x, t)
if (method == "e1") wt <- RLW.Ev1(x, t)
if (method == "ev1") wt <- RLW.Ev1(x, t)
if (method == "e2") wt <- RLW.Ev2(x, t)
if (method == "ev2") wt <- RLW.Ev2(x, t)
if (method == "e3") wt <- RLW.Ev3(x, t)
if (method == "ev3") wt <- RLW.Ev3(x, t)
if (is.null(wt)) stop("Unknown method")
return(wt)
}
RLW.eqSteps <- function(x, t) {
# Cumulative loss of species using the "equal-steps" weighting scheme
# Applies Equation 2
w <- sapply(x, function(y) ifelse(y %in% RLcateg$name,
which(RLcateg$name == y),
Inf))
return(as.vector(RLcateg$wt[w]))
}
RLW.A1 <- function(x, t) {
# Cumulative loss of species using the "A1" weighting scheme
return(LoS.A1(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.A2 <- function(x, t) {
# Cumulative loss of species using the "A2" weighting scheme
return(LoS.A2(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.B1 <- function(x, t) {
# Cumulative loss of species using the "B1" weighting scheme
return(LoS.B1(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.B2 <- function(x, t) {
# Cumulative loss of species using the "B2" weighting scheme
return(LoS.B2(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.C <- function(x, t) {
# Cumulative loss of species using the "C" weighting scheme
return(LoS.C(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.D <- function(x, t) {
# Cumulative loss of species using the "D" weighting scheme
return(LoS.D(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.Ev1 <- function(x, t) {
# Cumulative loss of species using version 1 of the "E" weighting scheme
return(LoS.Ev1(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.Ev2 <- function(x, t) {
# Cumulative loss of species using version 2 of the "E" weighting scheme
return(LoS.Ev2(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLW.Ev3 <- function(x, t) {
# Cumulative loss of species using version 3 of the "E" weighting scheme
return(LoS.Ev3(x, t) * max(RLcateg$wt, na.rm=TRUE))
}
RLI <- function(x, t = 0, method = weightingRLI) {
# Red List Index
# Applies Equation 1
rlw <- na.omit(RLW(x, t, method))
rli <- 1 - sum(rlw) / length(rlw) / max(RLcateg$wt, na.rm=TRUE)
attr(rli, "N") <- length(rlw)
return(rli)
}
LoS <- function(k, t, nsim = 0, method = weightingELS) {
# Loss of species, given Red List category k and generation time t
# (this is the cumulative loss of species, not threat-wise!)
# Note that the expected (mean) loss of species is returned if nsim <= 1,
# whereas nsim randomised losses of species are returned otherwise.
# In the latter case, both `k` and `t` have to be of length 1.
method <- tolower(method)
loss <- NULL
if (substr(method, 1, 2) == "eq") loss <- LoS.eqSteps(k, t, nsim)
if (method == "a1") loss <- LoS.A1 (k, t, nsim)
if (method == "a2") loss <- LoS.A2 (k, t, nsim)
if (method == "b") loss <- LoS.B1 (k, t, nsim)
if (method == "b1") loss <- LoS.B1 (k, t, nsim)
if (method == "b2") loss <- LoS.B2 (k, t, nsim)
if (method == "c") loss <- LoS.C (k, t, nsim)
if (method == "c1") loss <- LoS.C (k, t, nsim)
if (method == "d") loss <- LoS.D (k, t, nsim)
if (method == "d1") loss <- LoS.D (k, t, nsim)
if (method == "e") loss <- LoS.Ev1(k, t, nsim)
if (method == "e1") loss <- LoS.Ev1(k, t, nsim)
if (method == "ev1") loss <- LoS.Ev1(k, t, nsim)
if (method == "e2") loss <- LoS.Ev2(k, t, nsim)
if (method == "ev2") loss <- LoS.Ev2(k, t, nsim)
if (method == "e3") loss <- LoS.Ev3(k, t, nsim)
if (method == "ev3") loss <- LoS.Ev3(k, t, nsim)
if (is.null(loss)) stop("Unknown method")
return(loss)
}
LoS.Ev1 <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "E" weighting scheme (version 1)
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
tauL <- apply(rbind(apply(rbind(t * RLcateg$lowG[w], 100), 2, min),
RLcateg$lowT[w]), 2, max)
tauU <- apply(rbind(apply(rbind(t * RLcateg$uppG[w], 100), 2, min),
RLcateg$uppT[w]), 2, max)
# applying Equation 8:
R50L <- 1 - (1 - RLcateg$lowP[w])^(TimeFrame / tauL)
R50U <- 1 - (1 - RLcateg$uppP[w])^(TimeFrame / tauU)
# rounding downwards for tau > TimeFrame and upwards for tau < TimeFrame:
R50L <- ifelse(tauL > TimeFrame, f100(R50L), c100(R50L))
R50U <- ifelse(tauU > TimeFrame, f100(R50U), c100(R50U))
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], R50L, R50U))
} else {
return(randomiseDist(RLcateg$distr[w], R50L, R50U, nsim))
}
}
LoS.Ev2 <- function(k, t, nsim = 0) {
# Cumulative loss of species using version 2 of the "E" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
tauL <- apply(rbind(apply(rbind(t * RLcateg$lowG[w], 100), 2, min),
RLcateg$lowT[w]), 2, max)
tauU <- apply(rbind(apply(rbind(t * RLcateg$uppG[w], 100), 2, min),
RLcateg$uppT[w]), 2, max)
# applying (logit of!) Equation 8:
R50L <- logit(1 - (1 - RLcateg$lowP[w])^(TimeFrame / tauL))
R50U <- logit(1 - (1 - RLcateg$uppP[w])^(TimeFrame / tauU))
# shifting extinction probabilities "outwards":
R50L <- R50L + ifelse(RLcateg$wt[w] == 0, -100,
ifelse(RLcateg$wt[w] == 1, -0.6,
ifelse(RLcateg$wt[w] == 2, -0.3,
ifelse(RLcateg$wt[w] == 3, +0.3,
ifelse(RLcateg$wt[w] == 4, +0.6,
ifelse(RLcateg$wt[w] == 5, +100,
NA))))))
R50U <- R50U + ifelse(RLcateg$wt[w] == 0, -100,
ifelse(RLcateg$wt[w] == 1, -0.3,
ifelse(RLcateg$wt[w] == 2, +0.3,
ifelse(RLcateg$wt[w] == 3, +0.6,
ifelse(RLcateg$wt[w] == 4, +100,
ifelse(RLcateg$wt[w] == 5, +100,
NA))))))
# back-transforming and rounding:
R50L <- round(invlogit(R50L), 2)
R50U <- round(invlogit(R50U), 2)
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], R50L, R50U))
} else {
return(randomiseDist(RLcateg$distr[w], R50L, R50U, nsim))
}
}
LoS.Ev3 <- function(k, t, nsim = 0) {
# Cumulative loss of species using version 3 of the "E" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
tauL <- apply(rbind(apply(rbind(t * RLcateg$lowG[w], 100), 2, min),
RLcateg$lowT[w]), 2, max)
tauU <- apply(rbind(apply(rbind(t * RLcateg$uppG[w], 100), 2, min),
RLcateg$uppT[w]), 2, max)
# applying (logit of!) Equation 8:
R50L <- logit(1 - (1 - RLcateg$lowP[w])^(TimeFrame / tauL))
R50U <- logit(1 - (1 - RLcateg$uppP[w])^(TimeFrame / tauU))
# reducing extinction probabilities:
R50L <- R50L + ifelse(RLcateg$wt[w] == 0, -100,
ifelse(RLcateg$wt[w] == 5, +100,
-0.5))
R50U <- R50U + ifelse(RLcateg$wt[w] == 0, -100,
ifelse(RLcateg$wt[w] >= 4, +100,
-0.5))
# back-transforming and rounding:
R50L <- round(invlogit(R50L), 2)
R50U <- round(invlogit(R50U), 2)
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], R50L, R50U))
} else {
return(randomiseDist(RLcateg$distr[w], R50L, R50U, nsim))
}
}
LoS.eqSteps <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "equal-steps" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
return(rep(RLcateg$wt[w], max(1, nsim)) / max(RLcateg$wt, na.rm=TRUE))
}
LoS.A1 <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "A1" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
time <- sapply(sapply(t, min, 100 / 3) * 3, max, 10)
L <- round(RLcateg$lowA1[w]^(time / 10), 2)
U <- round(RLcateg$uppA1[w]^(time / 10), 2)
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
LoS.A2 <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "A2" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
time <- sapply(sapply(t, min, 100 / 3) * 3, max, 10)
L <- round(RLcateg$lowA2[w]^(time / 10), 2)
U <- round(RLcateg$uppA2[w]^(time / 10), 2)
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
LoS.B1 <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "B1" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
L <- 1 - RLcateg$lowB1[w] / RLcateg$lowB1[which(RLcateg$LC)]
U <- 1 - RLcateg$uppB1[w] / RLcateg$uppB1[which(RLcateg$LC)]
L <- ifelse(L > 0.5, f100(L), c100(L))
U <- ifelse(U > 0.5, f100(U), c100(U))
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
LoS.B2 <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "B2" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
L <- 1 - RLcateg$lowB2[w] / RLcateg$lowB2[which(RLcateg$LC)]
U <- 1 - RLcateg$uppB2[w] / RLcateg$uppB2[which(RLcateg$LC)]
L <- ifelse(L > 0.5, f100(L), c100(L))
U <- ifelse(U > 0.5, f100(U), c100(U))
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
LoS.C <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "C" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
L <- 1 - RLcateg$lowC[w] / RLcateg$lowC[which(RLcateg$LC)]
U <- 1 - RLcateg$uppC[w] / RLcateg$uppC[which(RLcateg$LC)]
L <- ifelse(L > 0.5, f100(L), c100(L))
U <- ifelse(U > 0.5, f100(U), c100(U))
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
LoS.D <- function(k, t, nsim = 0) {
# Cumulative loss of species using the "D" weighting scheme
w <- sapply(k, function(x) ifelse(x %in% RLcateg$name,
which(RLcateg$name == x),
Inf))
L <- 1 - RLcateg$lowD[w] / RLcateg$lowD[which(RLcateg$LC)]
U <- 1 - RLcateg$uppD[w] / RLcateg$uppD[which(RLcateg$LC)]
L <- ifelse(L > 0.5, f100(L), c100(L))
U <- ifelse(U > 0.5, f100(U), c100(U))
if (nsim < 2) {
# applying Equation 9:
return(meanDist(RLcateg$distr[w], L, U))
} else {
return(randomiseDist(RLcateg$distr[w], L, U, nsim))
}
}
meanDist <- function(D, L, U) return(
# Returns the arithmetic mean of the interval between L and U,
# given distribution D
ifelse(D == "unif", L * 0.50 + U * 0.50,
ifelse(D == "incr", L * 0.25 + U * 0.75,
ifelse(D == "decr", L * 0.75 + U * 0.25,
NA)))
)
randomiseDist <- function(D, L, U, N) {
# Returns N random numbers within interval between L and U,
# given distribution D
r <- NA
if (D == "unif") r <- runif(N, L, U) # Equation 12
if (D == "incr") r <- rIncr(N, U)
if (D == "decr") r <- rDecr(N, L )
return(r)
}
meanScope <- function(x, ignoreScope = !useScope) {
# Returns the arithmetic mean of scope, given a scope class
if (ignoreScope) {
return(1)
} else {
name <- extractScope(x)
m <- function(x) {
w <- which(Scope$name == x)
f <- Scope$distr[w]
L <- Scope$lower[w]
U <- Scope$upper[w]
B <- Scope$beta [w]
mS <- switch(f,
unif = L * 0.50 + U * 0.50,
incr = L * 0.25 + U * 0.75,
decr = L * 0.75 + U * 0.25,
beta = 2 / (B + 2),
NA)
}
return(round(as.vector(sapply(name, m)), 3))
}
}
randomiseScope <- function(n, x, ignoreScope = !useScope) {
# Returns n random numbers of scope, given a scope class
if (ignoreScope) {
return(1)
} else {
name <- extractScope(x)
m <- function(x) {
w <- which(Scope$name == x)
f <- Scope$distr[w]
L <- Scope$lower[w]
U <- Scope$upper[w]
B <- Scope$beta [w]
mS <- switch(f,
unif = runif(n, L, U),
incr = rIncr(n, U),
decr = rDecr(n, L ),
beta = rbeta(n, 2, B),
NA)
}
return(as.vector(sapply(name, m)))
}
}
meanSeverity <- function(x) {
# Returns the arithmetic mean of severity,
# given a severity class
name <- extractSeverity(x)
m <- function(x) {
w <- which(Severity$name == x)
f <- Severity$distr[w]
L <- Severity$lower[w]
U <- Severity$upper[w]
B <- Severity$beta [w]
mS <- switch(f,
unif = L * 0.50 + U * 0.50,
incr = L * 0.25 + U * 0.75,
decr = L * 0.75 + U * 0.25,
beta = 2 / (B + 2),
NA)
}
return(round(as.vector(sapply(name, m)), 3))
}
randomiseSeverity <- function(n, x) {
# Returns n random numbers of severity,
# given a severity class
name <- extractSeverity(x)
m <- function(x) {
w <- which(Severity$name == x)
f <- Severity$distr[w]
L <- Severity$lower[w]
U <- Severity$upper[w]
B <- Severity$beta [w]
mS <- switch(f,
unif = runif(n, L, U), # Equation 12
incr = rIncr(n, U), # Equation 13
decr = rDecr(n, L ), # Equation 14
beta = rbeta(n, 2, B), # Equation 15
NA)
}
return(as.vector(sapply(name, m)))
}
identifyYears <- function(RL) {
# Years for which Red List are available are identified
# from the column names which start with "Categ"
w <- which(substr(names(RL), 1, nchar(Categ)) == Categ &
!(names(RL) %contains% "."))
years <- numeric(0)
if (length(w)) {
for (i in w) {
y <- substr(names(RL)[i], nchar(Categ) + 1, nchar(names(RL)[i]))
if (all(unlist(strsplit(y, "")) %in% as.character(0:9))) {
years <- c(years, as.numeric(y))
} else {
years <- NA
}
}
} else {
year <- NA
}
if (any(is.na(years))) {
cat("ERROR: Years could not be identified!\n")
}
return(years)
}
identifyThreats <- function(RL, unknown = unknownThreat) {
# Threats reported in a Red List are identified
# from the column names which start with "Threat"
thr <- character()
w <- which(substr(names(RL), 1, nchar(Threat)) == Threat)
if (length(w)) {
thr <- unique(unlist(strsplit(unlist(RL[,w]), ",")))
thr <- unique(extractThreat(thr))
thr <- c(sort(thr) %-% unknown, unknown)
}
return(thr)
}
checkRL <- function(RL) {
# Checks whether the Red List data frame is compatible with the
# formatting requirements for the subsequent analyses.
# * Prints error or success messages.
# * Returns a vector of the Red List Categories used in the data frame.
OK <- TRUE
years <- identifyYears(RL)
if (any(is.na(years))) {
OK <- FALSE
} else {
# Check Red List Categories
RLCat <- unique(unlist(RL[, which(substr(names(RL), 1, nchar(Categ)) ==
Categ)])) %-% ""
if (all(RLCat %in% c(RedListCat, RedListCat %+% downlistSymbol))) {
RLCat <- unique(n0(RLCat))
cat("Red List Categories are OK.\n")
} else {
cat("ERROR: The datafile contains unexpected Red List Categories:\n" %+%
paste(sort(RLCat %-% RedListCat), collapse=", ") %+% "\n")
OK <- FALSE
} # RL categories
# Check the threat columns
if (all((Threat %+% years) %in% names(RL))) {
if (length(unlist(strsplit(unlist(strsplit(unlist(RL[, Threat %+% years]),
",")), ":"))) %% 4) {
cat("ERROR: Different threats for the same species need to be " %+%
"separated by commas;\nand each threat needs to contain name, " %+%
"timing, scope and severity, \nseparated by colons!\n")
OK <- FALSE
} else {
thr <- unique(unlist(strsplit(unlist(RL[, Threat %+% years]), ",")))
if (any(extractThreat(thr) %in% unknownThreat)) {
timing <- unique(extractTiming(thr))
if (any(timing %in% unknownTiming)) {
if (any(timing %in% inclTiming)) {
if (any(extractScope(thr) %in% unknownScope)) {
if (all(extractScope(thr) %in% Scope$name)) {
if (any(extractSeverity(thr) %in% unknownSeverity)) {
if (all(extractSeverity(thr) %in% Severity$name)) {
cat("Threat columns are OK.\n")
} else {
cat("ERROR: The following severities are undefined:\n")
cat(paste(unique(extractSeverity(thr) %-% Severity$name,
collapse = ", ")) %+% "\n")
OK <- FALSE
}
} else {
cat("WARNING: The severity \"" %+% unknownSeverity %+%
"\" does not occur in the dataset!\n")
OK <- FALSE
} # unknown severity missing?
} else {
cat("ERROR: The following scope(s) are undefined:\n")
cat(paste(unique(extractScope(thr) %-% Scope$name,
collapse = ", ")) %+% "\n")
OK <- FALSE
} # all scopes defined?
} else {
cat("WARNING: The scope \"" %+% unknownScope %+%
"\" does not occur in the dataset!\n")
OK <- FALSE
} # unknown scope missing?
} else {
cat("ERROR: None of the following timings occur in the dataset:\n")
cat(paste(inclTiming, collapse = ", ") %+% "\n")
OK <- FALSE
} # timings ok?
} else {
cat("WARNING: The timing \"" %+% unknownTiming %+%
"\" does not occur in the dataset!\n")
OK <- FALSE
} # unknown timing missing?
} else {
cat("WARNING: The threat factor \"" %+% unknownThreat %+%
"\" does not occur in the dataset!\n")
OK <- FALSE
} # unknown threat missing?
} # formatting ok
} else {
cat("ERROR: The following column name(s) were expected but not found:\n")
cat(paste((Threat %+% sort(years)) %-% names(RL), collapse = ", ") %+% "\n")
OK <- FALSE
} # threat columns
# Check the change columns
if (length(years) > 1) {
if (all((Change %+% sort(years)[-1]) %in% names(RL))) {
if (any(unlist(RL[, Change %+% sort(years)[-1]]) %in% realChange)) {
cat("Change columns are OK.\n")
} else {
cat("ERROR: No change in Red List Category has \"" %+%
paste(realChange, collapse = "\" or \"") %+% "\" as a reason!\n")
OK <- FALSE
} # real change missing
} else {
cat("ERROR: The following column name(s) were expected but not found:\n")
cat(paste(Change %+% sort(years)[-1], collapse = ", ") %+% "\n")
OK <- FALSE
} # columns missing?
} # > 1 year?
} # years ok
# Check the generation time column
if (GTime %in% names(RL)) {
cat("Generation time was found.\n")
} else {
cat("WARNING: The dataset lacks a column containing generation times!\n")
OK <- FALSE
} # generation time
# Summarise checks
if (OK) {
cat("\nEverything looks fine so far!\n")
} else {
cat("\nOne or more problem(s) were found that may preclude further analyses!\n")
} # summary
return(RLCat)
} # checkRL
n0 <- function(x, symbol = downlistSymbol) {
# "Uplisting" of downlisted species,
# i.e. downlisted species are raised by one Red List Category.
# Note that this function assumes:
# * that downlisting is indicated by "symbol" after the Red List Category,
# * that downlisting is always to the Red List Category immediately below.
for (i in which(!RLcateg$EX)) {
v <- which(x == (RLcateg$name[i] %+% symbol))
W <- RLcateg$wt[i]
j <- which(RLcateg$wt == min(RLcateg$wt[which(RLcateg$wt > W)],
na.rm = TRUE))[1]
x[v] <- RLcateg$name[j]
}
return(x)
}
uplist <- function(RL, symbol = downlistSymbol) {
# "Uplists" species that have been downlisted.
# This function works only for IUCN Red List Categories (specifically,
# LC, NT, VU and EN). Others are returned unmodified.
years <- identifyYears(RL)
for (y in years) {
RL[, Categ %+% y] <- n0(RL[, Categ %+% y], symbol = symbol)
}
return(RL)
}
downlist <- function(RL, symbol = downlistSymbol) {
# "Confirms" downlisting, i.e. removes the symbol for downlisting
years <- identifyYears(RL)
for (y in years) {
RL[, Categ %+% y] <- gsub(symbol, "", RL[, Categ %+% y], fixed = TRUE)
}
return(RL)
}
backCast <- function(RL, real = realChange) {
# "Back-casts" the most recent knowledge to earlier Red Lists
years <- sort(identifyYears(RL), decreasing = TRUE)
for (y1 in years) { # copy category columns
RL[, Categ %+% y1 %+% "." %+% y1] <- RL[, Categ %+% y1]
}
if (length(years) > 1) {
for (y1 in years[-1]) {
# y1 is the year _to_ which knowledge is back-cast
y1f <- min(years[years > y1])
# y1f is the year of the Red List following y1
for (y2 in rev(years[years > y1])) {
# y2 is the year _from_ which knowledge is back-cast
RL[ , Categ %+% y1 %+% "." %+% y2] <-
RL[, Categ %+% y1f %+% "." %+% y2]
for (i in 1:nrow(RL)) {
if (RL[i, Change %+% y1f] %=% real &&
RL[i, Categ %+% y1 ] %in% LC.EX &&
RL[i, Categ %+% y2 ] %in% LC.EX) {
RL[ i, Categ %+% y1 %+% "." %+% y2] <- RL[i, Categ %+% y1]
} # if change
} # i (rows)
} # y2
} # y1
} else { # if > 1 year
if (length(years)) { # only 1 Red List
cat("NB: There was no earlier Red List to back-cast to!\n")
} else { # no Red List - or wrong column names!
cat("NB: The dataset did not contain identifiable Red List Categories!\n")
}
}
return(RL)
} # backCast
calcLoss <- function(RL) {
# Adds columns to the Red List data frame which contain the species loss
# (or ecosystem loss), i.e. the extinction probabilities within 50 years
# for each species (or ecosystem)
years <- sort(identifyYears(RL))
if (GTime %in% colnames(RL)) {
if (!is.numeric(RL[, GTime])) {
RL[, GTime] <- as.numeric(RL[, GTime])
}
w <- which(is.na(RL[, GTime]))
if (length(w)) {
RL[w, GTime] <- 0
cat("NB: `NA` generation times have been set to 0.\n")
}
} else {
RL[, GTime] <- 0
cat("WARNING: All generation times were assumed to be < 1 year.\n")
}
for (y1 in years) {
for (y2 in years[years >= y1]) {
RL[, "Loss" %+% y1 %+% "." %+% y2] <-
LoS(RL[, Categ %+% y1 %+% "." %+% y2], RL[, GTime])
if (includeDD) { # assign probabilities of loss to DD species
for (i in which(isDD(RL[, Categ %+% y1 %+% "." %+% y2]))) {
RL[i, "Loss" %+% y1 %+% "." %+% y2] <- round(weighted.mean(
LoS(sort(LC.EX), rep(RL[i, GTime], length(LC.EX))),
table(RL[which(RL[, Categ %+% y1 %+% "." %+% y2] %in% LC.EX),
Categ %+% y1 %+% "." %+% y2])), 3)
} # i
} # if DD
} # y2
} # y1
return(RL)
} # calcLoss
addThreats <- function(RL) {
# Adds columns for each Red List and each threat to the data frame
years <- sort(identifyYears(RL))
threats <- identifyThreats(RL)
unknThr <- paste(unknownThreat,
inclTiming[1],
unknownScope,
unknownSeverity,
sep = ":")
for (y in years) {
t <- Threat %+% y
C <- Categ %+% y %+% "." %+% max(years)
RL[ threats %+% y] <- 0
RL[ "Pop" %+% y] <- 0
selection <- which(isConcern(RL[,C]))
if (includeDD) {
selection <- which(isConcern(RL[,C]) | isDD(RL[,C]))
}
for (i in selection) {
if (isExtinct(RL[i, C])) {
# For extinct species, all timings of threats are considered,
# i.e. they are re-coded as "ongoing"
if (nchar(RL[i, t])) {
P <- unlist(strsplit(RL[i, t], ","))
for (j in 1:length(P)) {
P[j] <- paste(extractThreat(P[j]),
inclTiming[1],
extractScope(P[j]),
extractSeverity(P[j]),
sep = ":")
}
RL[i, t] <- paste(P, collapse = ",")
} else {
RL[i, t] <- unknThr
}
} # if extinct
if (nchar(RL[i, t])) {
P <- unlist(strsplit(RL[i, t], ","))
if (any(extractTiming(P) %in% inclTiming)) {
# Keep only ongoing threats
P <- P[which(extractTiming(P) %in% inclTiming)]
} else {
# If there is no ongoing threat for a threatened species,
# an ongoing unknown threat is added
P <- unknThr
}
} else {
# If there is no threat at all for a threatened species,
# an ongoing unknown threat is added
P <- unknThr
}
for (j in 1:length(P)) {
# Threat factors receive score according to their scope and severity
ScoSev <- meanScope(P[j]) * meanSeverity(P[j])
# Scope * severity scores are summed for each species
RL[i, "Pop" %+% y] <- RL[i, "Pop" %+% y] + ScoSev
RL[i,extractThreat(P[j]) %+% y] <- RL[i,extractThreat(P[j]) %+% y] + ScoSev
} # j
} # i
} # y
return(RL)
} # addThreats
summariseRL <- function(RL, exclude = notEval) {
# Produces a summary table of the Red List(s) in the dataset
years <- sort(identifyYears(RL))
categ <- RedListCat %-% exclude
rows <- ""
i <- 0
if (length(years) > 0) {
tab <- matrix(as.numeric(NA),
length(years) * (length(years) + 1) / 2,
length(categ) + 3)
colnames(tab) <- c("N", categ, "RLI", "Cum.ELS" %+% TimeFrame)
for (y1 in years) {
for (y2 in years[years >= y1]) {
i <- i + 1
C <- Categ %+% y1 %+% "." %+% y2
tb <- table(RL[, C])
tab[i, categ] <- tb[categ]
tab[i, "N"] <- sum(tab[i, categ], na.rm=TRUE)
tab[i, "RLI"] <- RLI(RL[, C], RL[, GTime])
tab[i, "Cum.ELS" %+% TimeFrame] <-
sum(RL[, "Loss" %+% y1 %+% "." %+% y2], na.rm=TRUE)
if (y1 %=% y2) {
rows[i] <- "RL" %+% y1
} else {
rows[i] <- "RL" %+% y1 %+% "." %+% y2
}
} # y2
} # y1
rownames(tab) <- rows
print(tab)
} else {
cat("NB: There were no Red List data to summarise!\n")
tab <- NA
}
invisible(tab)
} # summariseRL
DeltaRLI <- function(RL) {
# Calculates DeltaRLI
# This requires a dataframe `RL` with Red List Categories and threats factors
# from more than one Red List.
# The output is a matrix with threat-wise DeltaRLI values for each combination
# of Red Lists, corrected for knowledge from the most recent Red List.
years <- sort(identifyYears(RL))
threats <- identifyThreats(RL)
if (length(years) > 1) {
DRLIp <- DRLIm <- matrix(0, length(threats), length(years),
dimnames = list(threats, "RL" %+% years)
)
W <- THR <- DW <- list()
for (y in years) {
categ <- Categ %+% y %+% "." %+% max(years)
W[[y]] <- RLW(RL[, categ], RL[, GTime])
} # y
L <- length(which(RL[, categ] %in% LC.EX))
for (p in threats) {
for (y in years) {
# applying Equation 3:
THR[[y]] <- RL[, p %+% y] /
ifelse(RL[, "Pop" %+% y] == 0, 1, RL[, "Pop" %+% y])
} # y
for (i in 2:length(years)) {
yr <- years[i]
y0 <- years[i - 1]
# applying Equation 5:
DW[[i]] <- W[[y0]] * THR[[y0]] - W[[yr]] * THR[[yr]]
# applying Equation 4 (separately for positive and negative DeltaRLI):
DRLIp[p, i] <- sum(DW[[i]][which(DW[[i]] > 0 & W[[yr]] != W[[y0]])],
na.rm=T) / L / RLW(extinct[1])
DRLIm[p, i] <- sum(DW[[i]][which(DW[[i]] < 0 & W[[yr]] != W[[y0]])],
na.rm=T) / L / RLW(extinct[1])
} # i
} # p
if (inferThreats) { # extrapolation to unknown threats
n <- length(threats) # this code requires "unknown" to be the last threat!
for (i in 2:length(years)) {
# applying Equation 11:
DRLIp[, i] <- DRLIp[, i] * (1 + DRLIp[n, i] / sum(DRLIp[1:(n - 1), i]))
DRLIm[, i] <- DRLIm[, i] * (1 + DRLIm[n, i] / sum(DRLIm[1:(n - 1), i]))
}
DRLIp[n, ] <- DRLIm[n, ] <- 0
} # extrapolation
DRLIpm <- DRLIp + DRLIm
DRLI <- matrix(0, length(threats), length(years) * (length(years)- 1) / 2)
cnames <- character()
k <- 0
for (i in (length(years) - 1):1) {
y1 <- years[i]
DR <- rep(0, length(threats))
for (j in (i + 1):length(years)) {
k <- k + 1
y2 <- years[j]
DR <- DR + DRLIpm[, j]
cnames <- c(cnames, "RL" %+% y1 %+% "_" %+% y2)
DRLI[, k] <- DR
}
}
dimnames(DRLI) <- list(threats, cnames)
return(DRLI)
} else {
cat("DeltaRLI can only be estimated if there are at least two Red Lists.\n")
return(NA)
}
} # DeltaRLI
dRLI <- function(RL, RLI = TRUE, ELS = TRUE) {
# Calculates dRLI and ELS50
# This requires a dataframe `RL` with Red List Categories and threats factors.
# The output is a list with two elements:
# * a matrix with threat-wise dRLI values for each Red List,
# * a matrix with threat-wise ELS50 values for each Red List.
years <- sort(identifyYears(RL))
threats <- identifyThreats(RL)
drli <- els <- matrix(0, length(threats), length(years),
dimnames=list(threats, "RL" %+% years))
for (y in years) {
C <- Categ %+% y %+% "." %+% max(years)
L <- length(which(RL[, C] %in% LC.EX))
Gw <- RLW(RL[, C], RL[, GTime])
if (includeDD) {
# extrapolate to DD species
L <- length(which(RL[, C] %in% c(LC.EX, DD)))
Gw[which(isDD(RL[, C]))] <- mean(Gw[which(!isDD(RL[, C]))], na.rm = TRUE)
}
for (p in threats) {
# applying Equation 3:
THR <- RL[, p %+% y] / ifelse(RL[, "Pop" %+% y] == 0, 1, RL[, "Pop" %+% y])
# applying Equation 6: