/
focalSpecies.R
367 lines (341 loc) · 13.2 KB
/
focalSpecies.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
#' Lists all species names from the data set
#'
#' Lists all species names from the data set.
#' @param x an object of class \sQuote{OrganizedBirds} or \sQuote{SummarizeBirds}.
#' @return a \code{vector} with all species names in the data set
#' @examples
#' OB <- organizeBirds(bombusObsShort, sppCol = "scientificName", simplifySppName = TRUE)
#' allSpp <- listSpecies(OB)
#' @export
#' @seealso \code{\link{summarizeBirds}}, \code{\link{exportBirds}}
listSpecies<-function(x){
if (class(x) == "OrganizedBirds") {
allSpecies <- sort(unique(as.character(x$spdf$scientificName)))
} else if (class(x) == "SummarizedBirds") {
overList <- x$overlaid
allSpecies <- sort(
as.character(
na.omit(
unique(
unlist(
lapply(overList,
function(x){
res <- ifelse(!is.na(x),
x$scientificName,
NA)
return(res)
}
)
)
)
)
)
)
} else {
stop("The object 'x' must be of class OrganizedBirds or SummarizedBirds.")
}
return(allSpecies)
}
#' Summarize records of a species among all visits
#'
#' A function to summarise records of a species among all visits. Returns number of grid cells with occurrences,
#' number of observations, number of visits, number of years and number of months with occurrences.
#' @param x an object of class \sQuote{SummarizeBirds}.
#' @param focalSp the focal sp to look for.
#' @return a \code{data.frame} with summary data for the focal species
#' @examples
#' \donttest{
#' OB <- organizeBirds(bombusObsShort, sppCol = "scientificName", simplifySppName = TRUE)
#' grid <- makeGrid(searchPolygon, gridSize = 10)
#' SB <- summariseBirds(OB, grid=grid)
#' allSpp <- listSpecies(SB)
#' focal <- "Bombus campestris"
#' focalSpSummary(SB, focalSp=focal)
#' }
#' @export
#' @seealso \code{\link{summarizeBirds}}, \code{\link{exportBirds}}
focalSpSummary <- function(x, focalSp=NULL){
if (class(x) != "SummarizedBirds") {
stop("The object 'x' must be of class SummarizedBirds.")
}
if (is.null(focalSp)) {
stop("Please, define the focal species to search for.")
}
visitCol <- attr(x, "visitCol")
allSpecies <- listSpecies(x)
wFocal <- match(focalSp, allSpecies)
wOverFocal <- unname(
unlist(
lapply(x$overlaid,
function(x) {
res <- ifelse(length(x)>1,
focalSp %in% x$scientificName,
FALSE)
return(res)
}
)
)
)
if(sum(wOverFocal) == 0) stop("The focal species was not found in the data set.")
overFocal <- x$overlaid[wOverFocal]
## if there is a column for presence then remove absences
if("presence" %in% colnames(overFocal[[1]]) ) {
overFocal <- lapply(overFocal,
function(x){
wNotPres <- which(x$presence != 1 | is.na(x$presence))
if(length(wNotPres)>1){
res <- x[-wNotPres,]
} else {
res <- x
}
return(res)
}
)
}
yearsAll <- sort(unique(lubridate::year(x$temporal)))
yearRng <- range(yearsAll) # range(unname(unlist(lapply(x$overlaid, FUN=function(x) x$year) )))
yearMax <- max(yearsAll)
yearMin <- min(yearsAll)
# wNonEmptyFocal <- unname(which(unlist(lapply(overFocal, nrow))>0))
# nCells <- length(wNonEmptyFocal)
# nObs <- sum(unlist(lapply(overFocal[wNonEmptyFocal], nrow)))
# visitsFocal <- unname(unlist(lapply(overFocal[wNonEmptyFocal], FUN=function(x) x[,visitCol]) ))
# nVis <- length(visitsFocal)
# yearsFocal <- sort(unique(unlist(lapply(overFocal[wNonEmptyFocal], FUN=function(x) x[,"year"]) )))
# monthsFocal <- sort(unique(unlist(lapply(overFocal[wNonEmptyFocal], FUN=function(x) x[,"month"]) )))
nCells <- sum(wOverFocal)
nObs <- sum(
unlist(
lapply(overFocal,
function(x){
res <- sum(x$scientificName == focalSp)
return(res)
}
)
)
)
visitsFocal <- unique(
unname(
unlist(
lapply(overFocal,
function(x){
x[x$scientificName == focalSp,visitCol]
}
)
)
)
)
nVis <- length(visitsFocal)
yearsFocal <- sort(
unique(
unlist(
lapply(overFocal,
function(x){
x[x$scientificName == focalSp,"year"]
}
)
)
)
)
monthsFocal <- sort(
unique(
unlist(
lapply(overFocal,
function(x){
x[x$scientificName == focalSp,"month"]
}
)
)
)
)
return(data.frame("species"=focalSp,
"nCells"=nCells,
"nObs"=nObs,
"nVis"=nVis,
"visitsUID"=paste(visitsFocal, collapse = ","),
"nYears"=length(yearsFocal),
"nMonths"=length(monthsFocal),
stringsAsFactors = FALSE))
}
#' Summarise all records for a species
#'
#' This function will produce a simple visual report for the obsrevation pattern
#' of the focal species. It shows grid cells with records on a map,
#' and bar charts with number of records per year and month.
#' @param x an object of class \sQuote{SummarizeBirds}.
#' @param focalSp the focal spp to look for.
#' @param long whether the map should be long or wide.
#' @param polygon (optional) an object of class \sQuote{sf},
#' \sQuote{SpatialPolygon} or \sQuote{SpatialPolygonDataFrame}. (Default is \code{NULL})
#' @param colVis color to plot visited gird cells
#' @param colPres color to plot grid cells where species is present
#' @param ... further plot parameters
#' @return a plot with a brief species summary
#' @examples
#' \donttest{
#' OB <- organizeBirds(bombusObsShort, sppCol = "scientificName", simplifySppName = TRUE)
#' grid <- makeGrid(searchPolygon, gridSize = 10)
#' SB <- summariseBirds(OB, grid=grid)
#' allSpp <- listSpecies(SB)
#' focal <- allSpp[2]
#' focalSpReport(SB, focalSp=focal)
#' }
#' @export
#' @seealso \code{\link{summarizeBirds}}, \code{\link{exportBirds}}
focalSpReport <- function(x,
focalSp = NULL,
long = TRUE,
polygon = NULL,
colVis = "grey",
colPres = "red", ...){
if (class(x) != "SummarizedBirds") {
stop("The object 'x' must be of class SummarizedBirds.")
}
if (is.null(focalSp)) {
stop("Please, define the focal species to search for.")
}
visitCol <- attr(x, "visitCol")
# wNonEmpty<-unname(which(unlist(lapply(x$overlaid, nrow))>0))
wNonEmpty <- attr(x, "nonEmptyGridCells")
allSpecies <- listSpecies(x)
wFocal <- match(focalSp, allSpecies)
if(!(focalSp %in% allSpecies)) stop(paste0("The focal species ", focalSp,
" was not found among the species names in the data set."))
# overFocal <- lapply(x$overlaid, FUN=function(x)return(x[x$scientificName==focalSp,]))
wOverFocal <- unname(
unlist(
lapply(x$overlaid,
function(x){
res <- ifelse(length(x)>1,
focalSp %in% x$scientificName,
FALSE)
return(res)
}
)
)
)
overFocal <- x$overlaid[wOverFocal]
yearsAll <- sort(unique(lubridate::year(x$temporal)))
yearRng <- range(yearsAll)
yearMax <- max(yearsAll)
yearMin <- min(yearsAll)
wNonEmptyFocal <- wOverFocal #unname(which(unlist(lapply(overFocal, nrow))>0))
nObs <- sum(
unlist(
lapply(overFocal,
function(x){
return(sum(x$scientificName == focalSp))
}
)
)
)
visitsFocal <- unique(
unname(
unlist(
lapply(overFocal,
function(x) {
x[x$scientificName == focalSp, visitCol]
}
)
)
)
)
nVis <- length(visitsFocal)
yearsFocal <- unname(
unlist(
lapply(overFocal,
function(x){
x[x$scientificName == focalSp,"year"]
}
)
)
)
yearsFocalTbl <- table( factor(yearsFocal,
levels = yearsAll) )
monthsFocal <- unname(
unlist(
lapply(overFocal,
function(x){
x[x$scientificName == focalSp,"month"]
}
)
)
)
monthsFocalTbl <- table( factor(monthsFocal,
levels=1:12,
labels = month.abb[1:12]) )
reportStrg <- paste0("Number of observations: ", nObs)
### check the polygon
if(!is.null(polygon)){
if (!any(class(polygon) %in% c("sf", "sfc","SpatialPolygons", "SpatialPolygonsDataFrame"))) {
warning("Entered polygon is not a sf, SpatialPolygon nor SpatialPolygonsDataFrame.")
polygon<-NULL
}else{
if (!any(class(polygon) %in% c("SpatialPolygons", "SpatialPolygonsDataFrame"))) {
polygon <- st_as_sf(polygon)
}
if (!any(st_geometry_type(polygon) %in% c("POLYGON", "MULTIPOLYGON"))) {
polygon <- polygon[which(st_geometry_type(polygon) %in% c("POLYGON", "MULTIPOLYGON")),]
}
## error no CRS
if (is.na(st_crs(polygon))) {
warning("The polygon has no coordinate projection system (CRS) associated")
polygon <- NULL
} else {
# Transform to SB$spatial projection
polygon <- st_transform(polygon,
crs = st_crs(x$spatial) )
}
}
}
oldpar <- par(no.readonly =TRUE)
on.exit(suppressWarnings(par(oldpar)))
layout(matrix(c(1,2,1,3), nrow = 2, byrow = long))
par(mar=c(1,1,1,1))
plot(x$spatial$geometry[wNonEmpty], col = colVis, border = NA, ...)
plot(x$spatial$geometry[wNonEmptyFocal], col = colPres, border = NA, add=TRUE)
if(!is.null(polygon)) plot(polygon, col=NA, border=1, lwd=2, add=TRUE)
mtext(focalSp, side=3, font = 3, line = -.5)
mtext(reportStrg, side=3, font = 1, line = -1.5, cex = .8)
legend("bottomleft", legend=c("visited", "present"), col = c(colVis, colPres), pch = 15, bty="n")
par(mar=c(3,4,1,1))
barplot(yearsFocalTbl, ylab = "n. visits", las=2)
par(mar=c(4,4,1,1))
barplot(monthsFocalTbl, ylab = "n. visits", las=2)
}
#' Summarize all records for a species
#'
#' A function that counts the number of observations, number of visits and number of grid cells with occurrences for all species.
#' @param x an object of class \sQuote{SummarizeBirds}.
#' @return a \code{data.frame} with summary data for each species
#' @examples
#'\donttest{
#' grid <- makeGrid(searchPolygon, gridSize = 10)
#' SB <- summarizeBirds(organizeBirds(bombusObsShort), grid=grid)
#' summSB <- speciesSummary(SB)
#' }
#' @export
#' @seealso \code{\link{summarizeBirds}}, \code{\link{exportBirds}}
speciesSummary <- function(x){
if (class(x) != "SummarizedBirds") {
stop("The object 'x' must be of class SummarizedBirds.")
}
allSpecies <- listSpecies(x)
res <- data.frame("species"=character(0),
"nCells"=numeric(0),
"nObs"=numeric(0),
"nVis"=numeric(0),
"visitsUID"=character(0),
"nYears"=numeric(0),
"nMonths"=numeric(0),
stringsAsFactors = FALSE)
tmp <- sapply(allSpecies,
function(y){
fsp <- focalSpSummary(x, focalSp = y)
message(y)
return(fsp)
}, simplify = FALSE)
res <- do.call(rbind, tmp)
rownames(res) <- NULL
return(res)
}