-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFISHBIO_NFP_STB_OccupancyModels_Approach1B_2019_300mm+.R
1880 lines (1631 loc) · 79.2 KB
/
FISHBIO_NFP_STB_OccupancyModels_Approach1B_2019_300mm+.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
# File description
# ---------------------------------------------------------------------------
# File-Name: FISHBIO_NFP_STB_OccupancyModels_Approach1B_2019_300mm+
# Version: v.
# Original Date: 27th Sep. 2021
# Last Edit Date: 5th April 2022
# Author: Will Ware
# Email(s): (1) [email protected]; (2) [email protected]
# Description: Prepares sampling of striped bass shorter than 300 mm
# fork lengths & associated variables for
# occupancy models using data from 2019
# changes:
# ------
# v.1 - a. data formatting building on objects imported from code sent by Matt
# b. attempting to align NAs for fish & associated variables by editing example code from Matt
# c. data formatting to prepare occupancy models
# v.2 - a. formation of unmarked frame for occupancy models
# b. developing dynamic, multi-season occupancy models
# c. ranking dynamic multi-season occupancy models
# d. developing multi-season occupancy models that altered one parameter at a time
# e. ranking multi-season occupancy models to select covariate combinations for dynamic, multi-season occupancy models
# d. running & comparing dynamic, multi-season occupancy models
# v.3 - a. formatting data to explore correlations between observation covariates
# b. binomial logistic regressions of observation covariate correlations
# c. variance inflation factor plots to visualize observation covariate correlations
# v.4 - a. creating yearly a site covariate from sampling date from a list object
# b. re-running & ranking dynamic, multi-season occupancy models
# v.5 - a. creating dataframes of compiled covariates for model predictions
# b. predicting occupancy model results with different dataframes
# v.6 - a. attempting to plot model predictions & editing plots
# v.7 - a. re-running & ranking dynamic, multi-season occupancy models based on Matt's new suggestions
# - b. predicting occupancy model results with a dataframe that Matt constructed for river kilometers, sampling days, & effort
# - c. visualizing model predictions & editing plots with Method I
# - d. Creating & visualizing model predictions with Method II
# - e. Adjusting model prediction plots to make them publication-quality
# v.8 - a. adding updated code on calculating VIF values for covariates b/c prior code was inconsistent with how covariate NAs were aligned
# Introduction
# -------------------------------------------------------------------------
# Approach 1B (as described by Matt) for 2019 striped bass
# from the Stanislaus "Native Fish Plan" sampling
# Note: striped bass are those below 300 mm fork length
# Run occupancy models on annual basis as above with robust design
# accounted for. This is one of the correct ways to examine these data.
# For this we should be very clear about what are primary events vs.
# secondary events (NOTE that these will change depending on later
# approaches that we may use). For 1b, 2019 data will have 4 primary
# events (PE), each with 2 secondary events (SE). E.g., PE1 will have SE1
# and SE2, PE2 will have SE1 and SE2, etc.
# Set Up
# ---------------------------------------------------------------------------
# clear items stored in global environment from prior code
rm(list = ls())
# load necessary packages
library(sp)
library(openxlsx)
library(dplyr)
library(tidyr)
library(ggplot2)
library(unmarked)
library(AICcmodavg)
library(xtable)
library(reshape2)
library(Hmisc)
# (also placed where applicable below)
# load R files from code developed by Matt & Tyler
# ensure the file is downloaded onto your computer &
# adjust reference folder for the load function, as needed
load("~/OneDrive - ucsc.edu/FISHBIO/Capstone Project/Occupancy Models/Approach 1B/2019/OccupancyData_09082021.Rdata")
# create the right reference data repository
setwd("~/OneDrive - ucsc.edu/FISHBIO/Capstone Project/Occupancy Models/Approach 1B/2019")
# Data formatting for striped bass less than 300 mm (fork length)
# -------------------------------------------------------------
# view detection data
cap.list.2019.gtSC$STB
# data not transformed to zeroes and ones
# filter out unneeded columns
stb.gt <-
cap.list.2019.gtSC$STB[, -c(1,2,3)]
# filter out the first 3 columns
# from striped bass less than 300 mm
# only want observations of striped bass
# convert counts to 0s & 1s for detection
stb.gt[c(1:39),] <-
ifelse(stb.gt[c(1:39),] == 0,0,1)
dimnames(stb.gt)[[2]] <- paste( "y", 1:ncol(stb.gt), sep=".")
# replace column names with "y.1" to "y.8" [8 columns total]
sum(na.exclude(stb.gt))
# calculate the total number of sampled striped bass
# longer than 300 mm fork lengths, excluding "NA" entries
# 29 NAs
# ensure all "NA" entries align
fishNAs <- which(is.na(stb.gt) == T )
# take NAs from striped bass observations
# make an object to store NAs from striped bass observations &
# observation covariates
allNAs <- unique(sort(c(fishNAs,
# add striped bass NAs to the NA collection
envNAs1.2019,
# add previously created object for flow NAs
envNAs2.2019,
# add previously created object for temperature NAs
envNAs3.2019,
# add previously created object for effort NAs
envNAs4.2019,
# add previously created object for turbidity NAs
envNAs5.2019,
# add previously created object for conductivity NAs
envNAs6.2019 )))
# add previously created object for sampling day NAs
# apply NAs from the compilation of all NA positions to each
# observation covariate
observation.covariates.2019.unscaled$flow[allNAs] <- NA
# flow
observation.covariates.2019.unscaled$temp[allNAs] <- NA
# temperature
observation.covariates.2019.unscaled$effort[allNAs] <- NA
# sampling effort
observation.covariates.2019.unscaled$turbidity[allNAs] <- NA
# turbidity
observation.covariates.2019.unscaled$conductivity[allNAs] <- NA
# conductivity
observation.covariates.2019.unscaled$day[allNAs] <- NA
# sampling day
# ensure striped bass data is a matrix
str(stb.gt) # dataframe
stb.gt <- as.matrix(stb.gt) # convert to matrix
str(stb.gt) # matrix
# apply all NA positions from each variable to striped bass observations
stb.gt[allNAs] <- NA
# check whether NAs are now aligned
length(which(is.na(stb.gt))) # striped bass observations = 32
length(allNAs) # all NA locations = 32 positions
# both are 32 values long, indicating that NAs from each are aligned
# Assess variable correlations, quantified by
# variance inflation factors then visualize results
# -------------------------------------------------------------------
# compile dataframe of covariates
flow <- observation.covariates.2019.unscaled$flow
flow.avg <- apply(flow[, c(1:8)], 1, function(x) mean(x, na.rm = T))
flow.means <- as.data.frame(flow.avg)
effort <- observation.covariates.2019.unscaled$effort
effort.avg <- apply(effort[, c(1:8)], 1, function(x) mean(x, na.rm = T))
effort.means <- as.data.frame(effort.avg)
day <- observation.covariates.2019.unscaled$day
day.avg <- apply(day[, c(1:8)], 1, function(x) mean(x, na.rm = T))
day.means <- as.data.frame(day.avg)
# compile columns for row means of observation covariates with river km
covars <- cbind(flow.means, effort.means, day.means,
site.covariates.scaled$rkm)
# rename columns for covariates
colnames(covars)[1] <- "flow"
colnames(covars)[2] <- "effort"
colnames(covars)[3] <- "day"
colnames(covars)[4] <- "rkm"
# model flow against other variables (effort, day, & river km)
cor_m1 <- lm(flow ~ effort+day+rkm, covars)
# variance inflation value calculation
library(performance)
check1 <- check_collinearity(cor_m1)
check1
# visualize results
library(see)
p1 <- plot(check1)
# model effort against other variables (flow, day, & river km)
cor_m2 <- lm(effort ~ flow+day+rkm, covars)
# variance inflation value calculation
library(performance)
check2 <- check_collinearity(cor_m2)
check2
# visualize results
library(see)
p2 <- plot(check2)
# model sampling day against other variables (flow, effort, & river km)
cor_m3 <- lm(day ~ flow+effort+rkm, covars)
# variance inflation value calculation
library(performance)
check3 <- check_collinearity(cor_m3)
check3
# visualize results
library(see)
p3 <- plot(check3)
# Developing occupancy model dataframe
# ---------------------------------------------------------
number.of.primary.periods <- 4
# set number of primary sampling periods
# (sampling events in 2019, in this case)
primaryperiods <- matrix(as.integer(rep(seq(1,number.of.primary.periods,1),
nrow(rkm.dat))),
ncol = number.of.primary.periods,
byrow = F) # do not fill the matrix by row
# construct site covariates for occupancy models from sampling days
# replace NAs for sampling date with column means
day <- observation.covariates.2019.unscaled$day
# dataframe for sampling days
day2.0 <- matrix(NA, nrow = 39, ncol = 8)
# matrix for site covariate
for (i in 1:8) {
# i = 1 # use this line & pick a number from 1:8 to check whether
# the for loop is correctly working
v <- day[,i]
# stand-in variable for column number
avg <- mean(v,na.rm = T)
# variable for column means
v[which(is.na(v))] <- avg
# replace NAs in each column with respective means
day2.0[,i] <- v
#
}
# create a matrix that selects the primary sampling events
# (first dates of each event)
yearlysitecovs = list(date = matrix(c(day2.0[,1],
day2.0[,3],
day2.0[,5],
day2.0[,7]),
nrow = 39,
byrow = F))
# view result
yearlysitecovs$date
# same result as viewing "yearlysitecovs" since "date" is
# the only variable
# model dataframe developed with "unmarkedMultFrame"
stb.gt.UMF <- unmarkedMultFrame(y = stb.gt,
# observed detections (initial occupancy)
siteCovs = site.covariates.scaled,
# use environmental variables -
# river km, sinuosity, max, stratification, depth, cv
obsCovs = observation.covariates.2019.unscaled,
yearlySiteCovs = yearlysitecovs,
numPrimary = number.of.primary.periods )
summary(stb.gt.UMF)
# Compare submodels that alter parameters for multi-season occupancy models
# ------------------------------------------------------------------------
# Explanation
# SEPARATELY alter initial occupancy, colonization, local
# extinction/persistence, & detection probabilities SEPARATELY by
# combinations of site & observation covariates to determine which
# ones produce the best functioning model FOR STRIPED BASS SMALLER THAN
# 300 MM FORK LENGTH
# Note:
# first-year occupancy can only be altered by site covariates
# colonization & extinction/persistence can only be altered by
# covariates that vary by site and season
# detection can be altered by covariates that vary by site, season, &
# observations
# ------------------------------------------------------------------------
# Adjustments on Matt's suggested code for
# dynamic, multi-season occupancy models
# models
dm0 <- colext( ~1, ~1, ~1, ~1, stb.gt.UMF)
# null model
dm1 <- colext( ~ 1, ~ 1, ~ 1, ~ flow, stb.gt.UMF)
# alter detection probability by flow
dm2 <- colext( ~ 1, ~ 1, ~ 1, ~ effort, stb.gt.UMF)
# alter detection probability by effort
dm3 <- colext( ~ 1, ~ 1, ~ 1, ~ flow + effort, stb.gt.UMF)
# alter detection probability by flow & effort
dm4 <- colext( ~ 1, ~ date, ~ 1, ~ flow, stb.gt.UMF)
# alter colonization probability by sampling date &
# detection probability by flow
dm5 <- colext( ~ 1, ~ date, ~ 1, ~ effort, stb.gt.UMF)
# alter colonization probability by sampling date &
# detection probability by sampling effort
dm6 <- colext( ~ 1, ~ date, ~ 1, ~ flow + effort, stb.gt.UMF)
# alter colonization probability by sampling date &
# detection probability by flow + sampling effort
dm7 <- colext( ~ rkm, ~ date, ~ 1, ~ flow, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date, &
# detection probability by flow
dm8 <- colext( ~ rkm, ~ date, ~ 1, ~ effort, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date, &
# detection probability by sampling effort
dm9 <- colext( ~ rkm, ~ date, ~ 1, ~ flow + effort, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date, &
# detection probability by flow + sampling effort
dm10 <- colext( ~ rkm, ~ date, ~ date, ~ flow, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date,
# extinction probability by sampling date, &
# detection probability by flow
dm11 <- colext( ~ rkm, ~ date, ~ date, ~ effort, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date,
# extinction probability by sampling date, &
# detection probability by sampling effort
dm12 <- colext( ~ rkm, ~ date, ~ date, ~ flow + effort, stb.gt.UMF)
# alter initial occupancy probability by river km,
# colonization probability by sampling date,
# extinction probability by sampling date, &
# detection probability by flow + sampling effort
modnames =
c('Null', # null model
'det~flow', # model 1
'det~effort', # model 2
'det~flow+effort', # model 3
'col~date, det~flow', # model 4
'col~date, det~effort', # model 5
'col~date, det~flow+effort', # model 6
'psi~rkm, col~date, det~flow', # model 7
'psi~rkm, col~date, det~effort', # model 8
'psi~rkm, col~date, det~flow+effort', # model 9
'psi~rkm, col~date, ext~date, det~flow', # model 10
'psi~rkm, col~date, ext~date, det~effort', # model 11
'psi~rkm, col~date, ext~date, det~flow+effort') # model 12
models = c(dm0, dm1, dm2, dm3, dm4, dm5, dm6,
dm7, dm8, dm9, dm10, dm11, dm12)
# store all of the models &
# their respective names as a list object
# develop the output that shows model comparisons
library(AICcmodavg)
mod.table <-
aictab(models, # list of models being compared
modnames, # names to reference models
second.ord = F, # use 1st-order AIC rather than 2nd-order
nobs = NULL, # calculate AICs by the total sample size
sort = T, # order models by AIC
c.hat = T) # show value to indicate overdispersion
mod.table <- as.data.frame(mod.table)
mod.table
# Export dataframe of method 2 model results to Excel file
write.xlsx(mod.table,
file = "C:/Users/wjowa/OneDrive - ucsc.edu/FISHBIO/Capstone Project/Occupancy Models/Approach 1B/2019/2019_STB<300mmFL_OccupancyModel_Results.xlsx",
sheetName = "Model Comparisons - Method 2",
overwrite = T)
dm2019_STBgt300_List <- fitList(fits = models)
dm2019_STBgt300_List
# convert the list object to a "fitList" object for
# model comparisons
# Extract values of interest from model summaries
coef(dm2019_STBgt300_List) # coefficients
SE(dm2019_STBgt300_List) # standard errors
# Model-averaged prediction
predict(dm2019_STBgt300_List, type = "psi")
# predict initial occupancy probabilities by
# averaging estimates across all models
predict(dm2019_STBgt300_List, type = "col")
# predict colonization probabilities by
# averaging estimates across all models
predict(dm2019_STBgt300_List, type = "ext")
# predict extinction probabilities by
# averaging estimates across all models
predict(dm2019_STBgt300_List, type = "det")
# predict detection probabilities by
# averaging estimates across all models
# Model selection
AICtable_2019_STBgt300 = modSel(dm2019_STBgt300_List, nullmod = "Null")
AICtable_2019_STBgt300
# ------------------------------------------------------------------------
# Visualize model results
# Plot initial occupancy probability & colonization probabilities across years
# develop dataset for "predictions" of initial occupancy probability
# use predict function get initial occupancy, colonization, &
# extinction estimates
library(stats)
# form dataframe for model predictions
nd = data.frame(rkm = seq(0, 65, length.out = 100),
# kilometers of the lower Stanislaus River
date = seq(60, 180, length.out = 100),
# sampling dates from March - May
effort = seq(100, 1500, length.out = 100))
# sampling effort range
E.occ <- predict(dm8, type = "psi", nd)
E.col <- predict(dm8, type = "col", nd)
E.det <- predict(dm8, type = "det", nd)
# Ploting method I
# large plots of initial occupancy, colonization, & detection probabilities
# -------------------------------------------------------------------------
# plotting settings
graphics.off() # don't plot
windows(7,6) # plotting window size
par(mar=c(4,4.8,1.5,2.1), # maximum plot margins
# adjusts bottom, left, top, & right margins (in order)
mfrow = c(1,1), # 1 rows & 1 column
mgp = c(1.5,0.2,0)) # axis labels relative to
# the edge of inner plot window
library(Hmisc) # package for plotting minor tick marks
# initial occupancy probability
with(E.occ,
{
plot(nd$rkm,
Predicted,
type = 'l',
pch = 1,
xaxt = "n",
xlab = "River kilometer",
main = "2019 initial occupancy of large striped bass",
ylab = expression(hat(psi)),
las = 1,
ylim = c(0,1), font.lab = 2, tck = 0.03,
cex.axis = 0.75)
axis(1, at = nd$rkm,
labels = round(seq(0, 65, length.out = 100),0),
tck = 0.03,
cex.axis = 0.75)
arrows(nd$rkm, lower, nd$rkm, upper, code = 3, angle = 90,
length = 0.03, col=rgb(0,0,0,0.2))
})
# colonization probability
with(E.col,
{
plot(nd$date,
Predicted,
type = 'l',
xaxt = "n",
xlab = "Sampling day",
main = "2019 colonization of large striped bass",
ylab = expression(hat(gamma)),
las = 1,
ylim = c(0,1), font.lab = 2, tck = 0.01, cex.axis = 0.75)
axis(1, at = nd$date,
labels = round(seq(60, 180, length.out = 100),0),
tck = 0.01, cex.axis = 0.75)
arrows(nd$date, lower, nd$date, upper, code = 3, angle = 90,
length = 0.03, col=rgb(0,0,0,0.2))
})
# detection probability
with(E.det,
{
plot(nd$effort,
Predicted,
type = 'l',
xaxt = "n",
xlab = "Electrofishing effort (s)",
main = "2019 detections of large striped bass",
ylab = expression(hat(p)),
las = 1,
ylim = c(0,1), font.lab = 2, tck = 0.03,
cex.axis = 0.75)
axis(1, at = nd$effort,
labels = round(seq(100, 1500, length.out = 100),0),
tck = 0.03 , cex.axis = 0.65)
arrows(nd$effort, lower, nd$effort, upper, code = 3, angle = 90,
length = 0.03, col = rgb(0,0,0,0.2))
})
# Plotting method II
# small plots of initial occupancy, colonization, & detection probabilities
# followed by a plot of "naive" & estimated "actual" occupancy
# -----------------------------------------------------------------------
# mean predicted occupancy among sites
boot_mod.gt19 <- nonparboot( dm8, B = 5 )
# 5x boostrap for the most parsimonious model for SE calculation
pred.gt19 <- data.frame( event = 1:4,
# initial occupancy before each primary sampling event
smoothed_occ = smoothed(dm8)[2,],
# smooth the curve for model estimates
SE = [email protected][2,] )
# extract basis set supersition error from
# smoothed model estimates
# make prediction plots here w/ respect to covariates of top model AND
# provide estimates and uncertainty of occupancy
par(mfrow = c(2,2), # 2 rows & 2 columns
mar = c(10,4,0.5,0.5)) # plot margin size settings
# adjusts bottom, left, top, & right margins (in order)
# predicted initial occupancy probability by river kilometer
plot(nd$rkm,
E.occ$Predicted,
type = 'l',
xaxt = "n",
ann = F,
ylim = c(0,1),
# plot probabilites along the y-axis from 0 to 1
tck = 0.01
)
axis(1, at = nd$rkm,
labels = round(seq(0, 65, length.out = 100),0),
tck = 0.01,
cex.axis = 0.75)
title(xlab = 'River kilometer',
ylab = expression(hat(psi)))
lines(nd$rkm, E.occ$lower, lty = 2)
lines(nd$rkm, E.occ$upper, lty = 2)
# predicted colonization probability by sampling day
plot(nd$date,
E.col$Predicted,
type = 'l',
xaxt = "n",
ann = F,
ylim = c(0,1),
# plot probabilites along the y-axis from 0 to 1
tck = 0.01
)
axis(1, at = nd$date,
labels = round(seq(60, 180, length.out = 100),0),
tck = 0.01,
cex.axis = 0.75)
title(xlab = "Sampling date",
ylab = expression(hat(gamma)))
lines(nd$date, E.col$lower, lty = 2)
lines(nd$date, E.col$upper, lty = 2)
# predicted detection probability by sampling effort
plot( nd$effort,
E.det$Predicted,
type = 'l',
xaxt = "n",
ann = F,
ylim = c(0,1),
# plot probabilites along the y-axis from 0 to 1
tck = 0.01
)
axis(1, at = nd$effort,
labels = round(seq(100, 1500, length.out = 100),0),
tck = 0.01,
cex.axis = 0.75)
title(xlab = 'Electrofishing effort (s)',
ylab = expression(hat(p)))
lines( nd$effort, E.det$lower, lty = 2)
lines( nd$effort, E.det$upper, lty = 2)
# comparison of predicted occupancy &
# occupancy based on detections, or "naive" occupancy
# adjust plot margins
par(oma = c(0, 0, 0, 7),
# adjusts outer margins
# bottom, left, top, & right margins (in order)
mar = c(4, 4, 2, 2),
# adjusts inner margins
# bottom, left, top, & right margins (in order)
mfrow = c(2,1))
# 2 rows, 1 column
# plotting
plot(pred.gt19$event,
pred.gt19$smoothed_occ,
ylim = c(0,1),
# plot probabilites along the y-axis from 0 to 1
tck = 0.01,
type = 'n',
las = 1,
xlab = "Primary sampling event",
ylab = "Occupancy",
main = "Large (FL ≥ 300 mm) striped bass occupancy in 2019",
axes = F)
# place box around plot area
box('plot')
# naive estimate of occupancy #
# calculate proportions of occupied sites
nums19gt <- apply(cap.list.2019.gtSC$STB[, -c(1:3)],
2, function(x) length(which( x > 0)))
ns19gt <- apply(cap.list.2019.gtSC$STB[, -c(1:3)],
2, function(x) 39 - length(which( is.na(x))))
props19gt <- nums19gt / ns19gt
# plot points depicting estimates of actual & "naive"
# occupancy at the start of each sampling event
# "naive" occupancy (doesn't account for detection %)
points(pred.gt19$event,
c(mean(props19gt[1:2]),
mean(props19gt[3:4]),
mean(props19gt[5:6]),
mean(props19gt[7:8])),
pch = 21, bg = 'grey80', cex = 2.1 )
# predicted occupancy, based on detections
points(pred.gt19$event,
pred.gt19$smoothed_occ,
pch = 21,
bg = 'grey50',
cex = 2.1 )
# confidence intervals for "naive" estimates
segments(pred.gt19$event,
# specify where upper limit will be sourced
pred.gt19$smoothed_occ + pred.gt19$SE,
# upper
pred.gt19$event,
# specify where lower limit will be sourced
pred.gt19$smoothed_occ - pred.gt19$SE,
# lower
lwd = 2, lend = 2)
# line thickness & line end
# axes
# x-axis
axis(side = 1, at = 1:4,
# bottom of plot & locations at x1 to x4
tck = 0.01,
# position of x-axis tick marks
labels = 1:4)
# primary sampling events
# y-axis
axis(side = 2, at = seq(0, 1, 0.2),
# left of plot at locations y0 to y1 by 0.2 increments
tck = 0.01,
# position of y-axis tick marks
labels = seq(0,1,0.2), las = 1)
# probability axis set (see above comment); using solid line
# legend
legend(x = 4, y = 2.1,
legend = c( 'Naive Estimate', 'Model Estimate'),
pch = 21,
pt.cex = 2,
pt.bg = c( 'grey80', 'grey50'),
bty = 'n',
y.intersp = 0.6,
xpd = NA)
# Obselete code (all code below this line)
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# NA handling
# Replace "NA" entries for observation & site covariates with columns means
# ------------------------------------------------------
# Align NAs from different dataframes for striped bass
# -----------------------------------------------------
# store NA entries for striped bass shorter than
# 300 mm fork length as an object
stb.lt.NAs <-
which(is.na(stb.lt) == T)
# Match NA entries for striped bass observations & covariates
flow2[stb.lt.NAs] <- NA
effort2[stb.lt.NAs] <- NA
day2[stb.lt.NAs] <- NA
# flow (cfs)
flow <- observation.covariates.2019.unscaled$flow
# save variable as dataframe object
apply(flow, 2, function(x)length(which(is.na(x))))
# count "NA" entries in each column
flow_means <- apply(flow, 2, function(x)mean(x, na.rm = T))
flow_means
# calculate column means
# column 1 mean = 4268.108
# column 2 mean = 4549.31
# column 3 mean = 4623.158
# column 4 mean = 4637.368
# column 5 mean = 3174.211
# column 6 mean = 3014.571
# column 7 mean = 1323.333
# column 8 mean = 1434.737
flow2 <- matrix(NA, nrow = 39, ncol = 8)
for (i in 1:8) {
# i = 1
# (sequentially pick 1-8)
v <- flow[,i]
avg <- mean(v,na.rm = T)
v[which(is.na(v))] <- avg
flow2[,i] <- v
}
colnames(flow2)[1:8] <- c("flow1", "flow2","flow3", "flow4",
"flow5", "flow6", "flow7", "flow8")
# rename dataframe columns
# sampling effort
effort <- observation.covariates.2019.unscaled$effort
# save variable as dataframe object
apply(effort, 2, function(x)length(which(is.na(x))))
# count "NA" entries in each column
effort_means <- apply(effort, 2, function(x)mean(x, na.rm = T))
effort_means
# calculate column means
# column 1 mean = 433.8176
# column 2 mean = 469.6236
# column 3 mean = 497.1053
# column 4 mean = 510.3224
# column 5 mean = 598.2895
# column 6 mean = 562.3257
# column 7 mean = 567.3077
# column 8 mean = 569.1053
effort2 <- matrix(NA, nrow = 39, ncol = 8)
for (i in 1:8) {
# i = 1
# (sequentially pick 1-8)
v <- effort[,i]
avg <- mean(v,na.rm = T)
v[which(is.na(v))] <- avg
effort2[,i] <- v
}
colnames(effort2)[1:8] <- c("effort1", "effort2","effort3", "effort4",
"effort5", "effort6", "effort7", "effort8")
# rename dataframe columns
# sampling day
day <- observation.covariates.2019.unscaled$day
# save variable as dataframe object
apply(day, 2, function(x)length(which(is.na(x))))
# count "NA" entries in each column
day_means <- apply(day, 2, function(x)mean(x, na.rm = T))
day_means
# calculate column means
# column 1 mean = 66.40541
# column 2 mean = 67.96774
# column 3 mean = 94.31579
# column 4 mean = 95.31579
# column 5 mean = 122.52632
# column 6 mean = 123.45714
# column 7 mean = 157.23077
# column 8 mean = 158.47368
day2.0 <- matrix(NA, nrow = 39, ncol = 8)
for (i in 1:8) {
# i = 1
# (sequentially pick 1-8)
v <- day[,i]
avg <- mean(v,na.rm = T)
v[which(is.na(v))] <- avg
day2.0[,i] <- v
}
colnames(day2.0)[1:8] <- c("day1", "day2","day3", "day4",
"day5", "day6", "day7", "day8")
# rename dataframe columns
# water temperature
wtemp <- observation.covariates.2019.unscaled$temp
# another object already named "temp", so
# save variable as dataframe object named "wtemp"
apply(wtemp, 2, function(x)length(which(is.na(x))))
# count "NA" entries in each column
wtemp_means <- apply(wtemp, 2, function(x)mean(x, na.rm = T))
wtemp_means
# calculate column means
# column 1 mean = 11.05135
# column 2 mean = 10.84516
# column 3 mean = 11.41053
# column 4 mean = 11.35789
# column 5 mean = 12.38947
# column 6 mean = 12.46571
# column 7 mean = 16.36154
# column 8 mean = 16.10526
wtemp2 <- matrix(NA, nrow = 39, ncol = 8)
for (i in 1:8) {
# i = 1
# (sequentially pick 1-8)
v <- wtemp[,i]
avg <- mean(v,na.rm = T)
v[which(is.na(v))] <- avg
wtemp2.0[,i] <- v
}
colnames(wtemp2.0)[1:8] <- c("temp1", "temp2","temp3", "temp4",
"temp5", "temp6", "temp7", "temp8")
# rename dataframe columns
# river kilometer
rkm <- as.data.frame(site.covariates.unscaled$rkm)
# save variable as dataframe object
apply(rkm, 2, function(x)length(which(is.na(x))))
# count "NA" entries in each column - no "NA" entries
colnames(rkm)[1] <- "rkm"
# rename the column header of "rkm" to river kilometer
# combine all 2019 observation covariates together
observationCovs <-
cbind(flow2, effort2, wtemp2, rkm)
observationCovs2 <-
observationCovs[-c(17:24)]
# Striped bass observation data formatting
# ------------------------------------------------------
View(stb.lt)
# notice how observed are recorded with counts
colnames(stb.lt)[1:8] <- c("detections1", "detections2","detections3",
"detections4", "detections5", "detections6",
"detections7", "detections8")
# rename dataframe columns
# Combine the dataframes of detections & covariates (observation & site)
# with "NA" entries replaced by column means together
# -----------------------------------------------------------------------
mod_dat <- cbind(stb.lt, flow2, day2.0, effort2, rkm)
# Evaluate collinearity between model covariates
# -----------------------------------------------------------------------
# create a dataframe for observation covariates from 2019
obscovs.2019 <-
as.data.frame(observation.covariates.2019.unscaled)
# select variables of interest from specific columns
obscovs.lt.2019 <- select(obscovs.2019,
1:8, # flow
17:24, # effort in seconds
41:48) # sampling day
# this will also represent yearly site covariate "date"
# from the model dataframes since that is every
# 2nd sampling day
# call object storing observation & site covariates of interest
mod_dat
# add a column representing the sampling site number
mod_dat$site <- c(13,18,23,28,33,38,45,50,56,61,67,79,84,89,
94,99,104,109,114,119,124,129,139,
144,149,154,159,164,169,174,186,191,
196,201,206,211,216,221,226)
# 39 sites sampled striped bass in 2019
# add a column representing the river bank at the sampling site
mod_dat$bank <- c("left","right","left","right","left","right","left",
"right","left","right","left","right","left","right",
"left","right","left","right","left","right","left",
"right","left","right","left","right","left","right",
"left","right","left","right","left","right","left",
"right","left","right","left")
# format observation and site covariates for linear models
# detail - convert data from "wide" to "long" format
# flow
# select columns representing flow from
# parent dataframe "mod_dat"
flow.2019 <- select(mod_dat, 1:8)
# stack flow observations on top of one another
library(reshape2)
flow.2.2019 <- melt(flow.2019)
# effort
# select columns representing effort from
# parent dataframe "mod_dat"
effort.2019 <- select(mod_dat, 17:24)
# stack effort observations on top of one another
library(reshape2)
effort.2.2019 <- melt(effort.2019)
# sampling day ("day")
# select columns representing sampling day from
# parent dataframe "mod_dat"
day.2019 <- select(obscovs.2019, 41:48)
# stack sampling day observations on top of one another
library(reshape2)
day.2.2019 <- melt(day.2019)
# river kilometer ("rkm")
# stack river km observations on top of one another
# parent dataframe "mod_dat"
rkm2 <- rep(rkm, 8)
# format sampled detections of striped bass in long format
stb.lt.2 <- melt(stb.lt)
# combine stacked datasets ("long format") together
mod_dat2 <- cbind(stb.lt.2, flow.2.2019,
effort.2.2019,day.2.2019,rkm.2.2019)
# rename columns containing values of interest
colnames(mod_dat2)[2] <- "observations"
colnames(mod_dat2)[4] <- "flow"
colnames(mod_dat2)[6] <- "effort"
colnames(mod_dat2)[8] <- "day"
colnames(mod_dat2)[9] <- "rkm"
# select columns of interest & overwrite the dataframe
# usually overwritting is not a good practice, but
# the parent dataframe is undesirable & is overwritten
# to reduce potential confusion
mod_dat3 <- select(mod_dat2,2,4,6,8,9)
# long-formatted data that will be used for linear
# models to assess variance inflation factors of variables
# used for occupancy models
# add sampling site & event names to the long-formatted
# dataframe of observed detection/non-detection & covariates
mod_dat3$site <- rep(site.covariates.unscaled$unit_name, 8)
# extract & replicate sample site names 8x
mod_dat3$event <- rep(seq(1:8),39)
# remove "NA" entries from presence/absence records in "mod_dat3"
# and save as a new dataframe
mod_dat4 <- mod_dat3[!is.na(mod_dat3$observations), ]
# calculate the proportion of striped bass presences & absences
# at all sampling sites
site_props <-
as.data.frame(prop.table(table(mod_dat4$observations, # observed presences
mod_dat4$site))) # by sampling site
# rename column headers
colnames(site_props)[1] <- "detections"
colnames(site_props)[2] <- "sites"
colnames(site_props)[3] <- "proportions"
# Exploratory data analyses
# plot the relationship between the proportion of observed presence
# sampling site & select variables used for occupancy models (covariates)
#-------------------------------------------------------------------------------------
# step 1: count & remove "NA" entries
length(which(is.na(mod_dat4$flow)))
# count
mod_dat5 <- mod_dat4[!is.na(mod_dat4$flow), ]
# remove rows of NA observations
# step 2: unique(site_props$site)
# notice how 39 sample sites remain, so observations
# at each site are still included despite removal of NA values
# 27 sampling sites of the 39 total sampling sites have presences
# 104L 109R 114L 119R 124L 129R 139L 144R 149L 154R 159L
# 169L 174R 18R 191R 201R 206L 211R 216L 221R 226L 56L
# 61R 67L 84L 89R 94L 99R
# step 3: change the variable "day" from a factor to a number to allow
# calculation of the mean
mod_dat5$day <- as.numeric(mod_dat5$day)
# step 4: calculate mean values of covariates for each of the 39 sample sites
# site 104L
site104L <- filter(mod_dat5, site == "104L")
mean(site104L$flow) # 3443.75
mean(site104L$effort) # 111
mean(site104L$rkm) # 36.9
mean(site104L$day) # 14.75
# site 109R
site109R <- filter(mod_dat5, site == "109R")
mean(site109R$flow) # 3911.667
mean(site109R$effort) # 100.6667
mean(site109R$rkm) # 35.4
mean(site109R$day) # 12.33333
# site 114L
site114L <- filter(mod_dat5, site == "114L")
mean(site114L$flow) # 3473.75
mean(site114L$effort) # 110.75
mean(site114L$rkm) # 33.9
mean(site114L$day) # 14.5
# site 119R