/
oor_ranking.R
88 lines (57 loc) · 2.54 KB
/
oor_ranking.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
# clear workspace
rm(list = ls ())
# load packages
pacman::p_load(raster, dismo, rgeos, sp, spdep)
# load functions
source('Z:/users/joshua/Snakebite/snakebite/bespoke_functions_cluster.R')
# read in snakelist
snake_list <- read.csv('Z:/users/joshua/Snakebite/snakebite/snake_list.csv',
stringsAsFactors = FALSE)
# list species for which we have occurrence data
spp_list <- list.files('Z:/users/joshua/Snakebite/output/species_occurrence_plots/species data/',
pattern = '*_raw.csv$',
full.names = FALSE)
combined <- NULL
for(i in 1:length(spp_list)){
# get species info from spp_list
spp_name <- as.character(spp_list[i])
spp_name <- gsub('_raw.csv', '', spp_name)
# inform progress
message(paste('Processing species ', i, ' of ', length(spp_list), ' (', spp_name, ') ', Sys.time(), sep = ""))
sub <- snake_list[snake_list$split_spp == spp_name, ]
if(spp_name == 'Lachesis_stenophrys'){
sub <- snake_list[snake_list$split_spp == 'Lachesis_stenophyrs', ]
}
data_out <- NULL
# read in EOR shapefile for each species, and dissolve if >1 polygon
raw_range <- shapefile(sub$shapefile_path)
# get presence records for species
dat_path <- paste0('Z:/users/joshua/Snakebite/output/species_occurrence_plots/species data/',
spp_name,
'_trimmed.csv')
locations <- read.csv(dat_path,
stringsAsFactors = FALSE)
# remove NA records
locations <- locations[!(is.na(locations$latitude)), ]
if(nrow(locations) !=0){
# turn into a spatial points dataframe
coordinates(locations) <- c("longitude", "latitude")
# project coordinates in same projection as shape
proj4string(locations) <- proj4string(raw_range)
distances <- apply(gDistance(locations, raw_range,byid = TRUE), 2, min)
in_range <- distances[distances == 0]
data_out <- data.frame(species = spp_name,
number_of_records = length(distances),
number_in_range = length(in_range),
number_out_of_range = (length(distances) - length(in_range)),
cumulative_distance = sum(distances))
}
if(!(vector.is.empty(data_out))){
combined <- rbind(combined,
data_out)
}
}
outpath <- paste0('Z:/users/joshua/Snakebite/output/species_occurrence_plots/oor_stats/combined_', Sys.Date(), '.csv')
write.csv(combined,
outpath,
row.names = FALSE)