34
R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution within a country or region 1 Developed by Maria Dias, BirdLife International 2 (ver. March 2017) 3 Methods for calculating national RLIs weighted by the fraction of each species’ distribution occurring within the country or region. 4 The Red List Index can be downscaled to show national and regional Red List Indices, weighted by the fraction of each species’ distribution occurring within 5 the country or region, building on the method published by Rodrigues et al. (2014) PLoS ONE 9(11): e113934. These show an index of aggregate survival 6 probability (the inverse of extinction risk) for all birds, mammals, amphibians, corals and cycads occurring within the country or region. The index shows 7 how well species are conserved in a country or region to its potential contribution to global species conservation. The index is calculated as: 8 9 RLI(t,u) = 1- , 10 where t is the year of comprehensive reassessment, u is the spatial unit (i.e. country), , is the weight of the global Red List category for species s at 11 time t (Least Concern =0, Near Threatened =1, Vulnerable =2, Endangered =3, Critically Endangered =4, Critically Endangered (Possibly Extinct) =5, Critically 12 Endangered (Possibly Extinct in the Wild) =5, Extinct in the Wild =5 and Extinct =5), WEX = 5 is the weight for Extinct species, is the fraction of the total 13 range of species s in unit u, and is the total range size of species s. 14 The index varies from 1 if the country has contributed the minimum it can to the global RLI (i.e., if the numerator is 0 because all species in the country are 15 LC) to 0 if the country has contributed the maximum it can to the global RLI (i.e., if the numerator equals the denominator because all species in the country 16 are Extinct or Possibly Extinct). 17 18 The taxonomic groups included are those in which all species have been assessed for The IUCN Red List of Threatened Species™ more than once. Red List 19 categories for years in which comprehensive assessments (i.e. those in which all species in the taxonomic group have been assessed) were carried out are 20 determined following the approach of Butchart et al. 2007; PLoS ONE 2(1): e140, i.e. they match the current categories except for those taxa that have 21 undergone genuine improvement or deterioration in extinction risk of sufficient magnitude to qualify for a higher or lower Red List category. 22 23 An aggregate Red List Index across all taxonomic groups for each country or region is calculated following Butchart et al. 2010 Science 328: 1164-1168. It is 24 calculated as the arithmetic mean of modelled Red List Indices for each taxonomic group. The latter are interpolated linearly for years between data points 25 and extrapolated linearly (with a slope equal to that between the two closest assessed points, except for corals) back to the earliest time point and 26 forwards to the present for years for which estimates are not available. The start year of the aggregated index is set as ten years before the first assessment 27

R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

  • Upload
    others

  • View
    6

  • Download
    0

Embed Size (px)

Citation preview

Page 1: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution within a country or region 1

Developed by Maria Dias, BirdLife International 2

(ver. March 2017) 3

Methods for calculating national RLIs weighted by the fraction of each species’ distribution occurring within the country or region. 4

The Red List Index can be downscaled to show national and regional Red List Indices, weighted by the fraction of each species’ distribution occurring within 5 the country or region, building on the method published by Rodrigues et al. (2014) PLoS ONE 9(11): e113934. These show an index of aggregate survival 6 probability (the inverse of extinction risk) for all birds, mammals, amphibians, corals and cycads occurring within the country or region. The index shows 7 how well species are conserved in a country or region to its potential contribution to global species conservation. The index is calculated as: 8 9

RLI(t,u) = 1- ∑ (𝑊𝑊(𝑡𝑡,𝑠𝑠)× 𝑟𝑟𝑠𝑠𝑠𝑠𝑅𝑅𝑠𝑠 )𝑠𝑠

𝑊𝑊𝐸𝐸𝐸𝐸×∑ (𝑟𝑟𝑠𝑠𝑠𝑠𝑅𝑅𝑠𝑠 )𝑠𝑠 10

where t is the year of comprehensive reassessment, u is the spatial unit (i.e. country), 𝑊𝑊(𝑡𝑡,𝑠𝑠) is the weight of the global Red List category for species s at 11 time t (Least Concern =0, Near Threatened =1, Vulnerable =2, Endangered =3, Critically Endangered =4, Critically Endangered (Possibly Extinct) =5, Critically 12 Endangered (Possibly Extinct in the Wild) =5, Extinct in the Wild =5 and Extinct =5), WEX = 5 is the weight for Extinct species, 𝑟𝑟𝑠𝑠𝑠𝑠 is the fraction of the total 13 range of species s in unit u, and 𝑅𝑅𝑠𝑠 is the total range size of species s. 14

The index varies from 1 if the country has contributed the minimum it can to the global RLI (i.e., if the numerator is 0 because all species in the country are 15 LC) to 0 if the country has contributed the maximum it can to the global RLI (i.e., if the numerator equals the denominator because all species in the country 16 are Extinct or Possibly Extinct). 17 18 The taxonomic groups included are those in which all species have been assessed for The IUCN Red List of Threatened Species™ more than once. Red List 19 categories for years in which comprehensive assessments (i.e. those in which all species in the taxonomic group have been assessed) were carried out are 20 determined following the approach of Butchart et al. 2007; PLoS ONE 2(1): e140, i.e. they match the current categories except for those taxa that have 21 undergone genuine improvement or deterioration in extinction risk of sufficient magnitude to qualify for a higher or lower Red List category. 22 23 An aggregate Red List Index across all taxonomic groups for each country or region is calculated following Butchart et al. 2010 Science 328: 1164-1168. It is 24 calculated as the arithmetic mean of modelled Red List Indices for each taxonomic group. The latter are interpolated linearly for years between data points 25 and extrapolated linearly (with a slope equal to that between the two closest assessed points, except for corals) back to the earliest time point and 26 forwards to the present for years for which estimates are not available. The start year of the aggregated index is set as ten years before the first assessment 27

Page 2: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

year for the taxonomic group with the latest starting point. Corals are not extrapolated linearly because declines are known to have been much steeper 28 subsequent to 1996 (owing to extreme bleaching events) than before. Therefore the rate of decline prior to 1996 is set as the average of the rates for the 29 other taxonomic groups. 30 31 The Red List Indices for each taxonomic group for each year are modelled to take into account various sources of uncertainty: (i) Data Deficiency: Red List 32 categories (from Least Concern to Extinct) are assigned to all Data Deficient species, with a probability proportional to the number of species in non-Data 33 Deficient categories for that taxonomic group. (ii) Extrapolation uncertainty: although Red List Indices are extrapolated linearly based on the slope of the 34 closest two assessed point, there is uncertainty about how accurate this slope may be. To incorporate this uncertainty, rather than extrapolating 35 deterministically, the slope used for extrapolation is selected from a normal distribution with a probability equal to the slope of the closest two assessed 36 points, and standard deviation equal to 60% of this slope (i.e., the CV is 60%). (iii) Temporal variability: the ‘true’ RLI likely changes from year to year, but 37 because assessments are repeated only at multi-year intervals, the precise value for any particular year is uncertain. To make this uncertainty explicit, the 38 Red List Index value for a given taxonomic group in a given year is assigned from a moving window of five years, centred on the focal year. Assessment 39 uncertainty cannot yet be incorporated into the index. Practically, these uncertainties are incorporated into the aggregated Red List Index as follows: Data 40 Deficient species are allotted a category as described above, and a Red List Index for each taxonomic group is calculated interpolating and extrapolating as 41 described above. A final Red List Index value is assigned to each taxonomic group for each year from a window of years as described above. Each such ‘run’ 42 produces a Red List Index for the complete time period for each taxonomic group, incorporating the various sources of uncertainty. One thousand such runs 43 is generated for each taxonomic group, and the mean is calculated. 44 45

This code requires the following input files (shapefile or CSV format): 46

47 1. Table "list_all_species_wshapes.csv": Metada table to aux the analyses. “mapped”=if map exists; “Shapefile”=name of the shapefile with the range 48

map; “subfolder” =folder where it is stored (assumed that the subfolder is in the folder defined in table “tbfolders.csv” – see above); “size”=size of 49 the shapefile (in Kb; only for non-combined shaped); “combinedshape”: if the layers are combined in a single shapefile (1) or in one shapefile per 50 species (0); “mapped”: 1 if the species has a range map to be included in the analyses (can be 0 in some cases – e.g. endemic species) 51

Scientific Group TaxonID Cat_latest year_Cat

mapped endemic

ordem shapefile subfolder size combinedshape

mappedf

Struthio camelus Bird 45020636 LC 2015 1

1 Struthio_camelus_45020636.shp Struthionidae 202.072 0 1

Zamia wallisii Cycad 2.14E+09 CR 2013 1 Colombia

24221 zamia_wallisii.shp Zamia 0.3 0 1

52

Page 3: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

2. Table "Iso_countries.csv": list of ISO codes, country names and respective regions/other classifications (note 0 values – not NA – for missing values 53 in “Region”, “Developing”,”LDC” and “LLDC_SIDS” fields) 54

ordem country_SIS countryname region1 ISO3 ISO_BL ISO_SDG uname_BL uname_SDG Region Developing LDC LLDC_SIDS

247 High Seas Areas Beyond National Jurisdiction High Seas ABNJ ABNJ ABNJ High Seas High Seas 0 0 0 0

202 Aruba Aruba Caribbean Islands

ABW ABW ABW Aruba Aruba Latin America & the Caribbean Developing 0 SIDS

55

3. Table "genuine_changes.csv": table with the details for species that have qualified for genuine changes in their IUCN Red List since the first 56 comprehensive assessment for the group. All categories in the Genuine changes file must match one of LC, NT, VU, EN, CR, CR(PE), CR(PEW), EW, or 57 EX. (Note DD and NE are not permitted) 58

Group Scientific Taxon ID Period cat_start cat_end start_year end_year

Bird Nothocercus nigrocapillus

22678160 08-12 LC VU 2008 2012

59

60

4. Table "Sp_cnts_pp_FINAL.csv": table with the proportion of each species’ distribution in each country. 61

Scientific TaxonID marine ISO3 pp ovl method batch

Abditomys latidens 15337 0 PHL 1 terrestrial vector_overlap batch8

62

The code outputs several graphs and tables with the results of the analyses (global RLI and per country – XXX = code for each country/region): 63

1. global_all_taxa.pdf: graph with the global RLI for each taxonomic group and aggregated 64 2. global_aggregated.pdf: graph with the global aggregated RLI 65 3. global_birds.pdf: graph with the global RLI for birds 66 4. XXX.csv: table with national rli values and 95% confidence intervals (qn05 and qn95) for each taxonomic group and year 67 5. XXX_crli.csv: table with national crli values and 95% confidence intervals (crli05 and crli95) for each taxonomic group and year 68 6. XXX_aggregated.pdf: graph with the national aggregated RLI 69 7. XXX_all_taxa.pdf: graph with the national RLI for each taxonomic group and aggregated 70

Page 4: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

8. XXX_birds.pdf: graph with the national RLI for birds 71 9. XXX_crli.pdf: graph with the national CRLI for each taxonomic group and aggregated 72 10. allcountries_RLI.csv: table with rli values and 95% confidence intervals (qn05 and qn95) for each country, taxonomic group and year (i.e., several 73

XXX.csv combined in one file) 74 11. allcountries_CRLI.csv table with crli values and 95% confidence intervals (crli05 and crli95) for each country, taxonomic group and year (i.e., several 75

XXX_crli.csv combined in one file) 76 12. RLI_all_countries.pdf (graphs XXX_all_taxa.pdf combined in a single file) 77

78

Text that is highlighted should be amended to give the appropriate folder names and file paths, number of randomisations (if this is to be adjusted), final 79 year and ISO code/region to use (see grey columns in file Iso_countries.csv below) . 80

# National RLIs calculator v1 26/06/2016 81

# Maria Dias/BirdLife International; [email protected] 82 # Script to calculate and plot the national RLIs 83 ## See formats of input tables above 84 85 ####################### Parameters that need to be set 86 wkfolder="ADD FOLDER NAME/LOCATION HERE" ## copy-paste the working folder, replacing "/" by "/" and ensuring no spaces before & after quotes 87 setwd(wkfolder) 88 89 finfolder="ADD FOLDER NAME/LOCATION HERE" ## copy-paste the location of the folder where the country files should be saved, replacing "/" by "/" and ensuring no 90 spaces before & after quotes 91 finfolder2="ADD FOLDER NAME/LOCATION HERE" ## copy-paste the location of the folder where the final plots should be saved, replacing "/" by "/" and ensuring no 92 spaces before & after quotes 93 94 isos=read.csv("Iso_countries.csv") ## file with ISO codes; should be stored in the wkfolder specified above 95 tabsp1=read.csv("list_all_species_wshapes.csv") ## file with the name of shapefiles and folders of the species' range maps; should be stored in the wkfolder specified 96 above 97 gench=read.csv("genuine_changes.csv") ### file with list of Red List genuine changes; should be stored in the wkfolder specified above 98 tbf1=read.csv("Sp_cnts_pp.csv") ## result of spatial analyses to estimate the proportion of the range of each species in each country 99 100 slopecv=.6 ### standard devidation of the slope 101 maxyear=2017 ### max year of the analyses 102

Page 5: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

repetitions=1000 ## n repetitions 103 iso2use="M49_Region" #ISO_SDG #ISO_BL #LLDC_SIDS #LDC #Region #Developing ### iso to use in the analyses; choose from those available in isos table 104 105 ############################## custom functions 106 107 lu=function (x=x) length(unique(x)) ## function to estimate the number of unique values in a vector 108 first=function (x=x) x[1] ## function to output the fisrt value of a vector 109 q95=function (x=x) quantile(x,.95) ## function to estimate the quantile 95% 110 q05=function (x=x) quantile(x,.05) ## function to estimate the quantile 5% 111 div0=function (x=x, y=y) trunc((x-1)/y)-((x-1)/y) ## function that outputs 0 if y-1 is divisible by x (aux open new devices in graphics outputs) 112 cinz=rgb(217/255,217/255,217/255,.4) ### grey transparent colour for the plots (in rgb) 113 114 #function to calculate global RLI 115 # nreps=number of repetitions; groups2=list of taxonomic groups to analyse; leftextrapol=if slope should be extrapolated to the left; saveleftslope=if left slope should be 116 saved; plotit=if each iteraction should be plotted 117 rlicalc=function (nreps=repetitions, groups2=groups2, years=years, leftextrapol=T, saveleftslope=T, plotit=F){ 118 119 rliTot=data.frame(group=rep(rep(groups2, each=length(years)),length(nreps)), year=rep(rep(years, length(groups2)), length(nreps)), 120 nrep=rep(1:nreps,each=length(years)*length(groups2)), rli=NA) 121 outpts=list() 122 123 if (saveleftslope) leftslopes=NULL 124 for (r in 1:nreps) 125 { 126 #r=1 127 for (g in 1:length(groups2)) 128 { 129 #g=1 130 group=as.character(groups2[g]) 131 #group="Bird" 132 rlig=data.frame() 133 group 134 tgroup=tabgrli[tabgrli$group==group,] 135 yearsa=sort(unique(tgroup$year)) 136 yearsa 137 138

Page 6: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

### years of assessment 139 for (y in 1:length(yearsa)) 140 { 141 #y=1 142 year=yearsa[y] 143 year 144 tb=tgroup[tgroup$year==year,] 145 tb=merge(tb,wts) 146 head(tb) 147 nrow(tb) 148 rli1=1-(sum(tb$wg)/(wex*nrow(tb))) 149 rli1 150 rlig=rbind(rlig, data.frame(group=group,year=year, rli=rli1)) 151 } ## ends years of assessment 152 rlig 153 154 ### intrapolation and extrapolation 155 156 dat=rlig 157 dat 158 #interpolation 159 yearsti=min(dat$year): max(dat$year) 160 irli=approx(dat$year, dat$rli, xout=yearsti, method="linear", rule=2:2)$y 161 irli 162 163 datf=data.frame(year=yearsti, rli=irli) 164 datf 165 #with(datf, plot(year, rli, xlim=c(1975,2018), ylim=c(0.6,1.2))) 166 167 #extrapolation # y=a+bx 168 #left 169 yearl=c(min(years)-2, min(years)-1, years[which(years<min(yearsti))]) 170 yearl 171 172 x1=sort(dat$year)[1:2] 173 x1 ### years 174

Page 7: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

y1=c(dat$rli[dat$year==x1[1]],dat$rli[dat$year==x1[2]]) 175 y1 ###rlis 176 nv=lm(y1~x1) 177 mnslp <- coef(nv)[2] 178 useslp <- rnorm(1, mnslp, sd=slopecv*abs(mnslp)) 179 if (leftextrapol==F) useslp <- meanleftslopes 180 irlel=y1[1] - (useslp*(x1[1] -(yearl))) 181 182 if (leftextrapol) leftslopes=c(leftslopes,useslp) 183 datf=rbind(datf, data.frame(year=yearl, rli=irlel)) 184 185 #with(datf, points(year, rli, col=2, pch=19, cex=.6)) 186 datf 187 188 #right 189 yearr=c(years[which(years>max(yearsti))],max(years)+1,max(years)+2) 190 yearr 191 192 x1=sort(dat$year)[(nrow(dat)-1):nrow(dat)] 193 x1 ## years 194 y1=c(dat$rli[dat$year==x1[1]],dat$rli[dat$year==x1[2]]) 195 y1 ### rlis 196 nv=lm(y1~x1) 197 mnslp <- coef(nv)[2] 198 useslp <- rnorm(1, mnslp, sd=slopecv*abs(mnslp)) 199 irler=y1[2] - (useslp*(x1[2] -(yearr))) 200 datf=rbind(datf, data.frame(year=yearr, rli=irler)) 201 #with(datf, points(year, rli, col=2, pch=19, cex=.6)) 202 203 datf=datf[order(datf$year),] 204 205 206 if (plotit) 207 { 208 if (r<30) win.graph() 209 with(datf, plot(year, rli, pch=19, col=2, main=paste(group,"s", sep=""))) 210

Page 8: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

with(datf[datf$year%in%yearsti,], points(year, rli, pch=19, col=4)) 211 } 212 213 restmw=NULL 214 for (m in 3:(nrow(datf)-2)) restmw=c(restmw, sample(datf$rli[(m-2):(m+2)],1)) 215 finalmw=restmw 216 rliTot[rliTot$group==group&rliTot$nrep==r,]$rli=finalmw 217 if (plotit) with(rliTot[rliTot$group==group&rliTot$nrep==r,], lines(year, rli, col=8)) 218 219 } #ends loop groups 220 } #ends loop nreps 221 222 outpts[[1]]=rliTot 223 if (saveleftslope) outpts[[2]]=mean(leftslopes) 224 225 return(outpts) 226 } 227 228 ###################### 229 230 isos$isof=isos[,which(names(isos)==iso2use)] 231 head(isos) 232 lu(isos$isof) 233 234 nrow(tbf1) 235 head(tbf1) 236 tbf1=merge(tbf1, isos[,c("ISO3","isof")]) 237 tbf1=merge(tbf1,tabsp1[,c("Scientific","Group","Cat_latest")], sort=F) 238 nrow(tbf1) 239 head(tbf1) 240 tbf1$iucn=tbf1$Cat_latest 241 tbf=tbf1[tbf1$iucn!="DD",] 242 nrow(tbf) 243 lu(tbf$isof) 244 245 unique(tbf$iucn) 246

Page 9: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

wts=data.frame(iucn=c("LC","NT","VU","EN","CR","CR(PE)","CR(PEW)","EW","EX", "DD"), wg=c(0,1,2,3,4,5,5,5,5,-1)) 247 248 # verify is all IUCN codes are correct 249 cds1=unique(tbf$iucn) 250 length(cds1) 251 length(cds1[cds1%in%wts$iucn]) ## should be the same as previous 252 253 cds1=unique(gench$cat_start) 254 length(cds1) 255 length(cds1[cds1%in%wts$iucn]) ## should be the same as previous 256 257 cds1=unique(gench$cat_end) 258 length(cds1) 259 length(cds1[cds1%in%wts$iucn]) ## should be the same as previous 260 261 #verify if all the scientific names in genuine file are correct and are in in sp-cnts table 262 sp1=unique(gench$Scientific) #tabf$RLC #gench$cat_start #gench$cat_end 263 length(sp1) 264 length(sp1[sp1%in%tbf$Scientific]) 265 sp1[!sp1%in%tbf$Scientific] ### species that are missing in the sp-cnts table after excluding the DD (but are in the genuine file) 266 267 sprich=with(tbf1, aggregate(Scientific, list(group=Group), lu)) 268 names(sprich)[length(sprich)]="rich" 269 sprich ### number of species per taxon 270 271 years=min(gench$start_year):maxyear 272 years 273 274 groups=unique(tbf$Group) 275 groups 276 277 ################## reconstruct past tables 278 pastables=data.frame() 279 for (g in 1:length(groups)) 280 { 281 #g=1 282

Page 10: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

group=as.character(groups[g]) 283 #group="Bird" 284 group 285 tbgn=gench[gench$Group==group,] 286 tball=tbf1[tbf1$Group==group,] ### al sp sp-cnts 287 nrow(tbgn) 288 head(tbgn) 289 yearsa=sort(unique(c(tbgn$start_year,tbgn$end_year))) 290 yearsa 291 yearsa2=yearsa[1:length(yearsa)-1] 292 yearsa2 293 tabsp=with(tabsp1[tabsp1$Scientific%in%tball$Scientific,], data.frame(Scientific=Scientific, iucn=Cat_latest)) 294 tabsp$year=max(yearsa) 295 head(tabsp) 296 297 sp1=unique(tball$Scientific) 298 length(sp1) 299 length(sp1[sp1%in%tabsp$Scientific]) 300 301 tabsp2=tabsp 302 tabspnew=tabsp 303 for (y in length(yearsa2):1) 304 { 305 #y=1 306 tabsp3=tabspnew 307 tabsp3$year=yearsa2[y] 308 t2ch=tbgn[tbgn$start_year==yearsa2[y],c("Scientific","cat_start")] 309 head(t2ch) 310 nrow(t2ch) 311 312 for (z in 1:nrow(t2ch)) 313 { 314 #z=1 315 tabsp3$iucn[tabsp3$Scientific==as.character(t2ch$Scientific[z])]=as.character(t2ch$cat_start[z]) 316 } 317 tabspnew=tabsp3 318

Page 11: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

tabsp2=rbind(tabsp2,tabsp3) 319 } 320 321 nrow(tabsp2)/lu(tabsp2$Scientific) ## should be the number of years of comprehensive assessments 322 tabsp2$group=group 323 324 pastables=rbind(pastables,tabsp2) 325 } 326 327 #write.csv(pastables, "pastables.csv", row.names=F) 328 #pastables=read.csv("pastables.csv") 329 wex=wts$wg[wts$iucn=="EX"] 330 head(pastables) 331 332 #### overlall RLI and estimate left slope for corals 333 334 ddsp=unique(pastables$Scientific[pastables$iucn=="DD"]) 335 tabgrli=pastables[!pastables$Scientific%in%ddsp,] 336 head(tabgrli) 337 unique(tabgrli$iucn) 338 339 groupsf=c(as.character(groups[groups!="Coral"]),"Coral") # to ensure that Corals will be the last (to use the mean slope for left extrapolation) 340 tt=proc.time() 341 342 # non-corals 343 344 groups2=as.character(groups[groups!="Coral"]) 345 rliTotGlobal_noncorals_list=rlicalc(nreps=repetitions, groups2=groups2, years=years, leftextrapol=T, saveleftslope=T, plotit=F) 346 347 rliTotGlobal_noncorals=rliTotGlobal_noncorals_list[[1]] 348 head(rliTotGlobal_noncorals) 349 tail(rliTotGlobal_noncorals) 350 351 meanleftslopes=rliTotGlobal_noncorals_list[[2]] 352 meanleftslopes 353 354

Page 12: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

### corals 355 356 rliTotGlobal_corals_list=rlicalc(nreps=repetitions, groups2="Coral", years=years, leftextrapol=F, saveleftslope=F, plotit=F) 357 rliTotGlobal_corals=rliTotGlobal_corals_list[[1]] 358 head(rliTotGlobal_corals) 359 tail(rliTotGlobal_corals) 360 361 rliTotGlobal=rbind(rliTotGlobal_noncorals,rliTotGlobal_corals) 362 363 rlitotagrs=with(rliTotGlobal, aggregate(rli,list(year=year, nrep=nrep), mean)) 364 names(rlitotagrs)[length(rlitotagrs)]="rli" 365 rlitotagrs$group="aggregated" 366 head(rlitotagrs) 367 368 rliTotF=rbind(rliTotGlobal,rlitotagrs[,c("group","year","nrep","rli")]) 369 head(rliTotF) 370 tail(rliTotF) 371 max(rliTotF$nrep) 372 max(rliTotF$rli) 373 374 resg=with(rliTotF, aggregate(rli, list(year=year, group=group), length)) 375 resg$rli=with(rliTotF, aggregate(rli, list(year=year, group=group), median))$x 376 resg$qn95=with(rliTotF, aggregate(rli, list(year=year, group=group), q95))$x 377 resg$qn05=with(rliTotF, aggregate(rli, list(year=year, group=group), q05))$x 378 resg 379 380 gs=unique(resg$group) 381 resgf=data.frame() 382 for (g in 1:lu(gs)) 383 { 384 #g=1 385 gs1=as.character(gs[g]) 386 gs1 387 if (gs1!="aggregated") yrs=min(gench$start_year[gench$Group==gs1]):max(gench$end_year[gench$Group==gs1]) else yrs=(max(with(gench, aggregate(start_year, 388 list(Group), min))$x)-10):maxyear 389 rli3=resg[resg$group==gs1&resg$year%in%yrs,] 390

Page 13: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

rli3=rli3[order(rli3$year),] 391 resgf=rbind(resgf,rli3) 392 } 393 head(resgf,20) 394 395 tab2plot=resgf 396 397 par(las=1) 398 with(tab2plot,plot(year,rli, ylim=c(min(qn05), max(qn95)), xlim=c(min(year), max(year)+4), type="n", xlab="Year", ylab="Red List Index of species survival")) 399 400 gs=unique(tab2plot$group[tab2plot$group!="aggregated"]) 401 lu(gs) 402 for (g in 1:length(gs)) 403 { 404 #g=1 405 gs1=as.character(gs[g]) 406 res2=tab2plot[tab2plot$group==gs1,] 407 with(res2,polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 408 } 409 with(tab2plot[tab2plot$group=="aggregated",], polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 410 411 for (g in 1:length(gs)) 412 { 413 gs1=as.character(gs[g]) 414 res2=tab2plot[tab2plot$group==gs1,] 415 with(res2,lines(year,rli, col=2, lwd=2)) 416 text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=.6, adj=c(0,0.5)) 417 } 418 with(tab2plot[tab2plot$group=="aggregated",], lines(year,rli, col=4, lwd=2)) 419 #abline(v=2015, lty=3, col=8) 420 #write.csv(resgf, "global_RLIs.csv", row.names=F) 421 #pastables=read.csv("pastables.csv") 422 #meanleftslopes=(-0.0009302144) 423 424 ##### 425 ### pdf with global rlis 426

Page 14: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

427 rlinew=resgf 428 pdfs=T 429 pdf1name=paste(finfolder2, "/","global","_all_taxa.pdf", sep="") 430 pdf1name 431 if (pdfs) pdf(file=pdf1name, width = 12, height = 10) 432 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 433 434 #graph all 435 miny=.15 436 topy=min(c(1.02, max(rlinew$qn95)*1.1)) 437 topy 438 basy=min(rlinew$qn05)*.99 439 difrgy=diff(range(basy, topy)) 440 if (difrgy<miny) { 441 basy=topy-miny 442 difrgy=diff(range(basy, topy))} 443 444 with(rlinew,plot(year,rli, ylim=c(basy*.99,topy), xlim=c(min(year), max(year)+1), type="n", xlab="Year", yaxt="n", ylab="Red List Index of species survival")) 445 #with(rlinew,plot(year,rli, ylim=c(0,topy), type="n", xlab="Year", yaxt="n", ylab="Red List Index of species survival", main=namect1)) 446 if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 447 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 448 449 gs=unique(rlinew$group[rlinew$group!="aggregated"]) 450 lu(gs) 451 for (g in 1:length(gs)) 452 { 453 #g=1 454 gs1=as.character(gs[g]) 455 res2=rlinew[rlinew$group==gs1,] 456 with(res2,polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 457 } 458 with(rlinew[rlinew$group=="aggregated",], polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 459 460 for (g in 1:length(gs)) 461 { 462

Page 15: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

gs1=as.character(gs[g]) 463 res2=rlinew[rlinew$group==gs1,] 464 with(res2,lines(year,rli, col=2, lwd=2)) 465 if (pdfs) text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=1, adj=c(0,0.5)) 466 } 467 with(rlinew[rlinew$group=="aggregated",], lines(year,rli, col=4, lwd=2)) 468 469 if (pdfs) dev.off() 470 471 #graph aggregated 472 pdf2name=paste(finfolder2,"/", "global","_aggregated.pdf", sep="") 473 pdf2name 474 if (pdfs) pdf(file=pdf2name, width = 12, height = 10) 475 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 476 477 ttuse=rlinew[rlinew$group=="aggregated",] 478 topy=min(c(1.02, max(ttuse$qn95)*1.1)) 479 basy=min(ttuse$qn05)*.99 480 difrgy=diff(range(basy, topy)) 481 if (difrgy<miny) { 482 basy=topy-miny 483 difrgy=diff(range(basy, topy))} 484 485 with(ttuse,plot(year,rli, yaxt="n", ylim=c(basy,topy), type="n", xlab="Year", ylab="Red List Index of species survival")) 486 with(ttuse, polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 487 with(ttuse, lines(year,rli, col=4, lwd=2)) 488 if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 489 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 490 491 if (pdfs) dev.off() 492 493 # graph birds 494 pdf3name=paste(finfolder2,"/", "global","_birds.pdf", sep="") 495 pdf3name 496 if (pdfs) pdf(file=pdf3name, width = 12, height = 10) 497 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,7,4,2), mgp=c(5, 1, 0)) 498

Page 16: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

499 ttuse=rlinew[rlinew$group=="Bird",] 500 501 if (nrow(ttuse)==0) plot(1:10, 1:10, type="n", main="no data for birds", xaxt="n", yaxt="n", xlab="", ylab="") 502 if (nrow(ttuse)>0){ 503 miny=.05 504 topy=min(c(1.02, max(ttuse$qn95)*1.001)) 505 basy=min(ttuse$qn05)*.999 506 difrgy=diff(range(basy, topy)) 507 #if (difrgy<miny) { 508 #basy=topy-miny 509 #difrgy=diff(range(basy, topy))} 510 511 with(ttuse,plot(year,rli, ylim=c(basy,topy), yaxt="n", type="n", xlab="", ylab="Red List Index of species survival")) 512 with(ttuse, polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 513 with(ttuse, lines(year,rli, col=2, lwd=2)) 514 if (difrgy<0.3) 515 { 516 if (difrgy<0.1) {axis(2, seq(0,1, by=.002))} else axis(2, seq(0,1, by=.05)) 517 } 518 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 519 } 520 par(mgp=c(3.5, 1, 0)) 521 title(xlab="Year") 522 523 if (pdfs) dev.off() 524 525 ############################################# 526 ### rlis per country 527 528 tt=proc.time() 529 530 nreps=repetitions 531 plotit=F 532 plotit2=T 533 finalrlis=data.frame() 534

Page 17: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

535 cts=unique(tbf1$isof) 536 lu(cts) 537 cts=cts[cts!="0"] 538 cts 539 tt=proc.time() 540 541 for (x in 1:length(cts)) #length(cts) 542 { 543 #x=1 544 #x=which(cts=="ABW") 545 cnt=cts[x] 546 cnt 547 print(paste(x, cnt)) 548 549 tbct=tbf1[tbf1$isof==cnt,] 550 551 groupsf=as.character(unique(tbct$Group)) 552 groupsf 553 554 rliext=data.frame(country=cnt, group=rep(rep(groupsf, each=length(years)),nreps), year=rep(rep(years, length(groupsf)),nreps), 555 nrep=rep(1:nreps,each=length(years)*length(groupsf)), rli=NA) 556 head(rliext) 557 tail(rliext) 558 559 for (r in 1: nreps) #nreps 560 { 561 print(paste(x, cnt, r)) 562 #r=1 563 564 for (g in 1:length(groupsf)) ### note that loop of groups has to be the first, to save the slopes to apply to corals 565 { 566 #g=1 567 group=as.character(groupsf[g]) 568 group 569 570

Page 18: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

spcnt=tbct[tbct$Group==group,] 571 572 lu(spcnt$Scientific) 573 nrow(spcnt) 574 575 spcnt2=with(spcnt, aggregate(pp, list(Scientific=Scientific), sum)) ## sum pp for species and country (could be split for marine/terrestrial or disjucnt polygons in 576 country/eez layer with multiple entries) 577 nrow(spcnt2) 578 names(spcnt2)[length(spcnt2)]="pp" 579 head(spcnt2) 580 max(spcnt2$pp) 581 spcnt2[spcnt2$pp==1,] ## endemic species 582 583 spcnt3=merge(spcnt2,pastables) 584 head(spcnt3) 585 tail(spcnt3) 586 nrow(spcnt3)/nrow(spcnt2) ## should be the number of years of assessment for this group 587 588 yearsa=sort(unique(spcnt3$year)) 589 yearsa 590 yearsa2=yearsa[1:length(yearsa)-1] 591 yearsa2 592 593 ### years of assessment 594 595 rlig=data.frame() 596 for (y in 1:length(yearsa)) 597 { 598 #y=1 599 year=yearsa[y] 600 year 601 602 tb=spcnt3[spcnt3$year==year,] 603 head(tb) 604 nrow(tb) 605 606

Page 19: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

unique(tb$iucn) 607 608 tb[tb$iucn=="DD",] 609 tb[!tb$iucn%in%c("DD", "LC"),] 610 tb[tb$iucn=="LC",] 611 612 tb=merge(tb,wts) 613 head(tb) 614 nrow(tb) 615 dds=tb$Scientific[tb$iucn=="DD"] 616 dds 617 tb[tb$iucn=="DD",] 618 allwgs=tb$wg[tb$wg>(-1)] 619 if (length(allwgs)==0) allwgs=0 620 if (length(dds)>0) for (d in 1:length(dds)) tb$wg[tb$Scientific==dds[d]]=sample(allwgs,1) 621 tb[tb$iucn=="DD",] 622 623 tb$wxpp=tb$wg*tb$pp 624 #tb$wxpp=5*tb$pp 625 head(tb) 626 627 sum(tb$wxpp) 628 wex*sum(tb$pp) 629 sum(tb$wxpp)/(wex*sum(tb$pp)) 630 1-round(sum(tb$wxpp)/(wex*sum(tb$pp)),7) 631 rli1=1-round((sum(tb$wxpp)/(wex*sum(tb$pp))),7) 632 rli1 633 crli=round((sum(tb$wxpp)/(wex*sprich$rich[sprich$group==group])),7) 634 rlig=rbind(rlig, data.frame(group=group,year=year, rli=rli1)) 635 636 if (y==1) tb1=tb 637 638 } ## ends loop year 639 rlig 640 dat=rlig 641 dat 642

Page 20: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

643 #interpolation 644 yearsti=min(dat$year): max(dat$year) 645 irli=approx(dat$year, dat$rli, xout=yearsti, method="linear", rule=2:2)$y 646 irli 647 648 datf=data.frame(year=yearsti, rli=irli) 649 datf 650 #with(datf, plot(year, rli, xlim=c(1975,2018), ylim=c(0.6,1.2))) 651 652 #extrapolation # y=a+bx 653 #left 654 yearl=c(min(years)-2, min(years)-1, years[which(years<min(yearsti))]) 655 yearl 656 657 x1=sort(dat$year)[1:2] 658 x1 ### years 659 y1=c(dat$rli[dat$year==x1[1]],dat$rli[dat$year==x1[2]]) 660 y1 ###rlis 661 nv=lm(y1~x1) 662 mnslp <- coef(nv)[2] 663 useslp <- rnorm(1, mnslp, sd=slopecv*abs(mnslp)) 664 if (group=="Coral") useslp <- meanleftslopes 665 irlel=y1[1] - (useslp*(x1[1] -(yearl))) 666 667 datf=rbind(datf, data.frame(year=yearl, rli=irlel)) 668 datf 669 670 #right 671 yearr=c(years[which(years>max(yearsti))],max(years)+1,max(years)+2) 672 yearr 673 674 x1=sort(dat$year)[(nrow(dat)-1):nrow(dat)] 675 x1 ## years 676 y1=c(dat$rli[dat$year==x1[1]],dat$rli[dat$year==x1[2]]) 677 y1 ### rlis 678

Page 21: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

nv=lm(y1~x1) 679 mnslp <- coef(nv)[2] 680 useslp <- rnorm(1, mnslp, sd=slopecv*abs(mnslp)) 681 irler=y1[2] - (useslp*(x1[2] -(yearr))) 682 datf=rbind(datf, data.frame(year=yearr, rli=irler)) 683 datf=datf[order(datf$year),] 684 685 if (plotit) 686 { 687 win.graph() 688 with(datf, plot(year, rli, pch=19, col=2, main=paste(group,"s", sep=""))) 689 with(datf[datf$year%in%yearsti,], points(year, rli, pch=19, col=4)) 690 } 691 692 restmw=NULL 693 for (m in 3:(nrow(datf)-2)) restmw=c(restmw, sample(datf$rli[(m-2):(m+2)],1)) 694 finalmw=restmw 695 rliext[rliext$group==group&rliext$nrep==r,]$rli=finalmw 696 if (plotit) with(rliext[rliext$group==group&rliext$nrep==r,], lines(year, rli, col=8)) 697 } # ends loop group 698 } # ends loop rep 699 700 head(rliext) 701 tail(rliext) 702 max(rliext$nrep) 703 max(rliext$rli) 704 705 rlitotagrs=with(rliext, aggregate(rli,list(year=year, nrep=nrep), mean)) 706 names(rlitotagrs)[length(rlitotagrs)]="rli" 707 rlitotagrs$group="aggregated" 708 rlitotagrs$country=cnt 709 head(rlitotagrs) 710 711 rliextF=rbind(rliext,rlitotagrs[,c("country","group","year","nrep","rli")]) 712 head(rliextF) 713 tail(rliextF) 714

Page 22: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

max(rliextF$nrep) 715 max(rliextF$rli) 716 717 resg=with(rliextF, aggregate(rli, list(year=year, group=group), length)) 718 resg$rli=with(rliextF, aggregate(rli, list(year=year, group=group), median))$x 719 resg$qn95=with(rliextF, aggregate(rli, list(year=year, group=group), q95))$x 720 resg$qn05=with(rliextF, aggregate(rli, list(year=year, group=group), q05))$x 721 head(resg) 722 723 resg$rli[resg$rli>1]=1 724 resg$rli[resg$rli<0]=0 725 resg$qn95[resg$qn95>1]=1 726 resg$qn95[resg$qn95<0]=0 727 resg$qn05[resg$qn05>1]=1 728 resg$qn05[resg$qn05<0]=0 729 730 gs=unique(resg$group) 731 resgf=data.frame() 732 for (g in 1:lu(gs)) 733 { 734 #g=1 735 gs1=as.character(gs[g]) 736 gs1 737 if (gs1!="aggregated") yrs=min(gench$start_year[gench$Group==gs1]):max(gench$end_year[gench$Group==gs1]) else yrs=(max(with(gench, aggregate(start_year, 738 list(Group), min))$x)-10):maxyear 739 rli3=resg[resg$group==gs1&resg$year%in%yrs,] 740 rli3=rli3[order(rli3$year),] 741 resgf=rbind(resgf,rli3) 742 } 743 head(resgf,30) 744 745 final=resg 746 final$country=cnt 747 head(final) 748 finalrlis=rbind(finalrlis,final) 749 750

Page 23: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

final2save=final[, c("country","group","year","rli","qn05","qn95")] 751 finalname=paste(finfolder, "/", cnt,".csv", sep="") 752 finalname 753 write.csv(final2save,finalname, row.names=F) 754 755 if (plotit2){ 756 if (div0(x,6)==0) 757 { 758 win.graph(50,30) 759 par(mfrow=c(2,3), mar=c(2,2,2,1)) 760 } 761 762 tab2plot=resgf 763 with(tab2plot,plot(year,rli, ylim=c(min(qn05), max(qn95)), xlim=c(min(year), max(year)+4), type="n", xlab="Year", ylab="Red List Index of species survival", main=cnt)) 764 765 gs=unique(tab2plot$group[tab2plot$group!="aggregated"]) 766 lu(gs) 767 for (g in 1:length(gs)) 768 { 769 #g=1 770 gs1=as.character(gs[g]) 771 res2=tab2plot[tab2plot$group==gs1,] 772 with(res2,polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 773 } 774 with(tab2plot[tab2plot$group=="aggregated",], polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 775 776 for (g in 1:length(gs)) 777 { 778 gs1=as.character(gs[g]) 779 res2=tab2plot[tab2plot$group==gs1,] 780 with(res2,lines(year,rli, col=2, lwd=2)) 781 text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=.6, adj=c(0,0.5)) 782 } 783 with(tab2plot[tab2plot$group=="aggregated",], lines(year,rli, col=4, lwd=2)) 784 } 785 } # ends loop country 786

Page 24: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

787 print((proc.time()-tt)[1]/60) ## time in minutes 788 789 str(finalrlis) 790 head(finalrlis) 791 lu(finalrlis$country) 792 max(finalrlis$x) 793 max(finalrlis$rli) 794 min(finalrlis$rli) 795 796 ####################################################################################################### 797 798 ### combine all files in 1 (in case the country files are calculated in different machines, to save time 799 cmbfiles=F 800 801 if(cmbfiles){ 802 allfics=data.frame() 803 fics=dir("//AZ-FILESERVER2/gis_data/Tracking Ocean Wanderers/IUCN_R_scripts/RLI/country_files/ISO_BL_test/", pattern = ".csv", full.names =T) ### copy paste here the 804 folder with the countries' files 805 for (u in 1:length(fics)) allfics=rbind(allfics, read.csv(fics[u])) 806 lu(allfics$country) 807 finalrlis=allfics 808 } 809 810 str(finalrlis) 811 head(finalrlis) 812 lu(finalrlis$country) 813 max(finalrlis$rli) 814 815 816 ################################################### 817 ## country final files and graphs 818 iso2use 819 sumspp=with(tbf1, aggregate(pp, list(country=isof, group=Group), sum)) 820 names(sumspp)[length(sumspp)]="sumpp" 821 head(sumspp) 822

Page 25: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

sum(sumspp$sumpp) 823 824 rliextf=finalrlis 825 min(rliextf$rli) 826 max(rliextf$rli) 827 head(rliextf) 828 tail(rliextf) 829 830 pdfs=T 831 plotit=T 832 writefiles=T 833 if (pdfs) plotit=F 834 835 allcountries_RLI=data.frame() 836 allcountries_CRLI=data.frame() 837 838 cts=unique(rliextf$country) 839 length(cts) 840 841 #graphics.off() 842 for (i in 1:length(cts)) #length(cts) 843 { 844 #i=1 845 #i=which(cts=="ABW") 846 i 847 848 ct1=as.character(cts[i]) 849 ct1 850 rli2=rliextf[rliextf$country==ct1,] 851 852 namect1=as.character(ct1) 853 if (iso2use=="ISO_BL") namect1=paste(isos$uname_BL[isos$isof==as.character(ct1)][1] ," (", ct1, ")", sep="") 854 if (iso2use=="ISO_SDG") namect1=paste(isos$uname_SDG[isos$isof==as.character(ct1)][1] ," (", ct1, ")", sep="") 855 namect1 856 857 858

Page 26: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

gs=unique(rli2$group) 859 lu(gs) 860 861 rlinew=data.frame() 862 crlis=data.frame() 863 for (g in 1:lu(gs)) 864 { 865 #g=1 866 gs1=as.character(gs[g]) 867 gs1 868 if (gs1!="aggregated") yrs=min(gench$start_year[gench$Group==gs1]):max(gench$end_year[gench$Group==gs1]) else yrs=(max(with(gench, aggregate(start_year, 869 list(Group), min))$x)-10):maxyear 870 rli3=rli2[rli2$group==gs1&rli2$year%in%yrs,] 871 rli3=rli3[order(rli3$year),] 872 873 if (gs1!="aggregated") 874 { 875 crli1=rli2[rli2$group==gs1,] 876 crli1$crli=crli1$rli*sumspp$sumpp[sumspp$group==gs1&sumspp$country==ct1][1]/sprich$rich[sprich$group==gs1] 877 crli1$crli05=crli1$qn05*sumspp$sumpp[sumspp$group==gs1&sumspp$country==ct1][1]/sprich$rich[sprich$group==gs1] 878 crli1$crli95=crli1$qn95*sumspp$sumpp[sumspp$group==gs1&sumspp$country==ct1][1]/sprich$rich[sprich$group==gs1] 879 crlis=rbind(crlis,crli1[,c("country","group","year","crli","crli05","crli95")]) 880 } 881 rlinew=rbind(rlinew,rli3) 882 } 883 rlinew 884 tail(crlis) 885 886 crlisag=with(crlis, aggregate(crli, list(country=country, year=year), mean)) 887 888 names(crlisag)[length(crlisag)]="crli" 889 crlisag$group="aggregated" 890 crlisag$crli05=with(crlis, aggregate(crli05, list(country=country, year=year), mean))$x 891 crlisag$crli95=with(crlis, aggregate(crli95, list(country=country, year=year), mean))$x 892 893 yrs=(max(with(gench, aggregate(start_year, list(Group), min))$x)-10):maxyear 894

Page 27: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

crlisag=crlisag[crlisag$year%in%yrs,] 895 crlisag 896 crlisag[,c("country","group","year","crli","crli05","crli95")] 897 898 crlisf=data.frame() 899 gs2=unique(crlis$group) 900 for (g in 1:length(gs2)) 901 { 902 gs1=as.character(gs2[g]) 903 yrs=min(gench$start_year[gench$Group==gs1]):max(gench$end_year[gench$Group==gs1]) 904 crlisf=rbind(crlisf, crlis[crlis$group==gs1&crlis$year%in%yrs,]) 905 } 906 crlisf=rbind(crlisf,crlisag) 907 908 rlinew2save=rlinew[, c("country","group","year","rli","qn05","qn95")] 909 fnamect=paste(finfolder2, "/", ct1,".csv", sep="") 910 fnamect 911 if (writefiles) write.csv(rlinew2save,fnamect, row.names=F) 912 913 fnamect2=paste(finfolder2,"/", ct1,"_crli.csv", sep="") 914 fnamect2 915 if (writefiles) write.csv(crlisf,fnamect2, row.names=F) 916 917 allcountries_RLI=rbind(allcountries_RLI,rlinew2save) 918 allcountries_CRLI=rbind(allcountries_CRLI,crlisf) 919 920 if (plotit) { 921 if (div0(i,4)==0) 922 { 923 win.graph(30,20) 924 par(las=1, mfrow=c(4,4)) 925 } 926 } 927 928 pdf1name=paste(finfolder2, "/", ct1,"_all_taxa.pdf", sep="") 929 pdf1name 930

Page 28: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

if (pdfs) pdf(file=pdf1name, width = 12, height = 10) 931 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 932 933 #graph all 934 miny=.15 935 topy=min(c(1.02, max(rlinew$qn95)*1.1)) 936 topy 937 basy=min(rlinew$qn05)*.99 938 difrgy=diff(range(basy, topy)) 939 if (difrgy<miny) { 940 basy=topy-miny 941 difrgy=diff(range(basy, topy))} 942 943 with(rlinew,plot(year,rli, ylim=c(basy*.99,topy), xlim=c(min(year), max(year)+1), type="n", xlab="Year", yaxt="n", ylab="Red List Index of species survival")) 944 if (plotit) title(main=namect1) 945 #with(rlinew,plot(year,rli, ylim=c(0,topy), type="n", xlab="Year", yaxt="n", ylab="Red List Index of species survival", main=namect1)) 946 if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 947 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 948 949 gs=unique(rlinew$group[rlinew$group!="aggregated"]) 950 lu(gs) 951 for (g in 1:length(gs)) 952 { 953 #g=1 954 gs1=as.character(gs[g]) 955 res2=rlinew[rlinew$group==gs1,] 956 with(res2,polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 957 } 958 with(rlinew[rlinew$group=="aggregated",], polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 959 960 for (g in 1:length(gs)) 961 { 962 gs1=as.character(gs[g]) 963 res2=rlinew[rlinew$group==gs1,] 964 with(res2,lines(year,rli, col=2, lwd=2)) 965 #res22=rli2[rli2$group==gs1,] 966

Page 29: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

#with(res22,lines(year,rli, col=2, lwd=1)) 967 if (plotit) text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=.6, adj=c(0,0.5)) 968 if (pdfs) text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=1, adj=c(0,0.5)) 969 } 970 with(rlinew[rlinew$group=="aggregated",], lines(year,rli, col=4, lwd=2)) 971 972 if (pdfs) dev.off() 973 974 #graph aggregated 975 pdf2name=paste(finfolder2, "/", ct1,"_aggregated.pdf", sep="") 976 pdf2name 977 if (pdfs) pdf(file=pdf2name, width = 12, height = 10) 978 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 979 980 ttuse=rlinew[rlinew$group=="aggregated",] 981 topy=min(c(1.02, max(ttuse$qn95)*1.1)) 982 basy=min(ttuse$qn05)*.99 983 difrgy=diff(range(basy, topy)) 984 if (difrgy<miny) { 985 basy=topy-miny 986 difrgy=diff(range(basy, topy))} 987 988 with(ttuse,plot(year,rli, yaxt="n", ylim=c(basy,topy), type="n", xlab="Year", ylab="Red List Index of species survival")) 989 with(ttuse, polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 990 with(ttuse, lines(year,rli, col=4, lwd=2)) 991 if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 992 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 993 994 if (pdfs) dev.off() 995 996 # graph birds 997 pdf3name=paste(finfolder2,"/", ct1,"_birds.pdf", sep="") 998 pdf3name 999 if (pdfs) pdf(file=pdf3name, width = 12, height = 10) 1000 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 1001 1002

Page 30: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

ttuse=rlinew[rlinew$group=="Bird",] 1003 1004 if (nrow(ttuse)==0) plot(1:10, 1:10, type="n", main="no data for birds", xaxt="n", yaxt="n", xlab="", ylab="") 1005 if (nrow(ttuse)>0){ 1006 topy=min(c(1.02, max(ttuse$qn95)*1.1)) 1007 basy=min(ttuse$qn05)*.99 1008 difrgy=diff(range(basy, topy)) 1009 if (difrgy<miny) { 1010 basy=topy-miny 1011 difrgy=diff(range(basy, topy))} 1012 1013 with(ttuse,plot(year,rli, yaxt="n", ylim=c(basy,topy), type="n", xlab="Year", ylab="Red List Index of species survival")) 1014 with(ttuse, polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 1015 with(ttuse, lines(year,rli, col=2, lwd=2)) 1016 if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 1017 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 1018 } 1019 if (pdfs) dev.off() 1020 1021 1022 ### crli 1023 1024 pdf3name=paste(finfolder2, "/", ct1,"_crli.pdf", sep="") 1025 pdf3name 1026 if (pdfs) pdf(file=pdf3name, width = 12, height = 10) 1027 if (pdfs) par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,6,4,2), mgp=c(4.5, 1, 0)) 1028 1029 with(crlisf,plot(year,crli, ylim=c(min(crli05),max(crli05)), xlim=c(min(year), max(year)+1), type="n", xlab="", ylab="National contribution to the global RLI")) 1030 par(mgp=c(3.5, 1, 0)) 1031 title(xlab="Year") 1032 1033 gs=unique(crlisf$group[crlisf$group!="aggregated"]) 1034 lu(gs) 1035 for (g in 1:length(gs)) 1036 { 1037 #g=1 1038

Page 31: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

gs1=as.character(gs[g]) 1039 res2=crlisf[crlisf$group==gs1,] 1040 with(res2,polygon(c(year,rev(year)),c(crli05,rev(crli95)), col=cinz, border=cinz)) 1041 } 1042 with(crlisf[crlisf$group=="aggregated",], polygon(c(year,rev(year)),c(crli05,rev(crli95)), col=cinz, border=cinz)) 1043 1044 for (g in 1:length(gs)) 1045 { 1046 gs1=as.character(gs[g]) 1047 res2=crlisf[crlisf$group==gs1,] 1048 with(res2,lines(year,crli, col=2, lwd=2)) 1049 #res22=rli2[rli2$group==gs1,] 1050 #with(res22,lines(year,rli, col=2, lwd=1)) 1051 if (plotit) text(max(res2$year)+0.5, res2$crli[nrow(res2)],paste(gs1,"s", sep=""), cex=.6, adj=c(0,0.5)) 1052 if (pdfs) text(max(res2$year)+0.5, res2$crli[nrow(res2)],paste(gs1,"s", sep=""), cex=1, adj=c(0,0.5)) 1053 } 1054 with(crlisf[crlisf$group=="aggregated",], lines(year,crli, col=4, lwd=2)) 1055 1056 if (pdfs) dev.off() 1057 1058 } 1059 # ends loop countries 1060 1061 lu(allcountries_RLI$country) 1062 lu(allcountries_CRLI$country) 1063 1064 rliallcntsfile=paste(finfolder2,"/", "allcountries_RLI.csv", sep="") 1065 if (writefiles) write.csv(allcountries_RLI,rliallcntsfile, row.names=F) 1066 1067 crliallcntsfile=paste(finfolder2,"/", "allcountries_CRLI.csv", sep="") 1068 if (writefiles) write.csv(allcountries_CRLI,crliallcntsfile, row.names=F) 1069 1070 ###### single pdf with all plots 1071 1072 pdfallname=paste(finfolder2,"/", "RLI_all_countries.pdf", sep="") 1073 pdfallname 1074

Page 32: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

pdf(file=pdfallname, width = 12, height = 10) 1075 par(las=1,cex.axis=1.2, cex.lab=1.3, cex.main=1.5, mar=c(5,5,4,2), mgp=c(3.5, 1, 0)) 1076 1077 cts=unique(allcountries_RLI$country) 1078 for (i in 1:length(cts)) #length(cts) 1079 { 1080 #i=1 1081 #i=which(cts=="ABW") 1082 i 1083 1084 ct1=as.character(cts[i]) 1085 ct1 1086 rli2=rliextf[rliextf$country==ct1,] 1087 1088 namect1=as.character(ct1) 1089 if (iso2use=="ISO_BL") namect1=paste(isos$uname_BL[isos$isof==as.character(ct1)][1] ," (", ct1, ")", sep="") 1090 if (iso2use=="ISO_SDG") namect1=paste(isos$uname_SDG[isos$isof==as.character(ct1)][1] ," (", ct1, ")", sep="") 1091 namect1 1092 1093 fspct=pastables[pastables$Scientific%in%unique(tbf1$Scientific[tbf1$isof==ct1]),] 1094 head(fspct) 1095 respc=with(fspct, aggregate(year, list(iucn=iucn, year=year, group=group), length)) 1096 1097 rlinew=allcountries_RLI[allcountries_RLI$country==ct1,] 1098 1099 1100 #graph all 1101 miny=.15 1102 topy=min(c(1.02, max(rlinew$qn95)*1.1)) 1103 topy 1104 basy=min(rlinew$qn05)*.99 1105 difrgy=diff(range(basy, topy)) 1106 if (difrgy<miny) { 1107 basy=topy-miny 1108 difrgy=diff(range(basy, topy))} 1109 with(rlinew,plot(year,rli, ylim=c(basy*.99,topy), xlim=c(min(year), max(year)+1), type="n", xlab="Year", yaxt="n", ylab="Red List Index of species survival", main=namect1)) 1110

Page 33: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution

if (difrgy<0.3) axis(2, seq(0,1, by=.05)) 1111 if (difrgy>0.3) axis(2, seq(0,1, by=.1)) 1112 gs=unique(rlinew$group[rlinew$group!="aggregated"]) 1113 lu(gs) 1114 for (g in 1:length(gs)) 1115 { 1116 #g=1 1117 gs1=as.character(gs[g]) 1118 res2=rlinew[rlinew$group==gs1,] 1119 with(res2,polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 1120 } 1121 with(rlinew[rlinew$group=="aggregated",], polygon(c(year,rev(year)),c(qn05,rev(qn95)), col=cinz, border=cinz)) 1122 for (g in 1:length(gs)) 1123 { 1124 gs1=as.character(gs[g]) 1125 res2=rlinew[rlinew$group==gs1,] 1126 with(res2,lines(year,rli, col=2, lwd=2)) 1127 text(max(res2$year)+0.5, res2$rli[nrow(res2)],paste(gs1,"s", sep=""), cex=1, adj=c(0,0.5)) 1128 } 1129 with(rlinew[rlinew$group=="aggregated",], lines(year,rli, col=4, lwd=2)) 1130 1131 } 1132 dev.off() 1133

Page 34: R code to calculate and plot national RLIs weighted by the … · 2017-03-13 · 1 . R code to calculate and plot national RLIs weighted by the proportion of each species’ distribution