-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.R
More file actions
1327 lines (1126 loc) · 55.4 KB
/
app.R
File metadata and controls
1327 lines (1126 loc) · 55.4 KB
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
library(shiny)
library(shinyWidgets)
library(tidyverse)
library(sf)
library(leaflet)
library(DT)
library(leafpop)
library(FSA)
library(knitr)
library(ggtext)
# library(periscope)
# Module code
plotDownloadUI <- function(id, height = 400) {
ns <- NS(id)
tagList(
fluidRow(
column(
2, offset = 10,
downloadButton(ns("download_plot"), "Download plot")
)
),
fluidRow(
plotOutput(ns('plot'), height = height)
)
)
}
plotDownload <- function(input, output, session, plotFun) {
output$plot <- renderPlot({
plotFun()
})
output$download_plot <- downloadHandler(
filename = function() {
"plot.png"
},
content = function(file) {
ggsave(file, plotFun(), width = 9, height = 6)
}
)
}
# Read in summary fish metrics
metrics <- read_csv('standardized_fish_data.csv') %>%
relocate(area) %>%
relocate(N, .after = last_col()) %>%
mutate(gcat = case_when(gcat == "Stock-Quality" ~ "S-Q",
gcat == "Quality-Preferred" ~ "Q-P",
gcat == "Preferred-Memorable" ~ "P-M",
gcat == "Memorable-Trophy" ~ "M-T",
gcat == "Trophy" ~ "T") %>%
factor(levels = c("S-Q", "Q-P", "P-M", "M-T", "T"))) %>%
mutate(method = str_replace_all(method, " ", "_"),
waterbody_type = str_replace_all(waterbody_type, " ", "_"),
metric = str_replace_all(metric, "CPUE distance", "CPUE")) %>%
filter(method %in% c("boat_electrofishing", "raft_electrofishing", "gill_net_fall", "gill_net_spring", "drifting_trammel_net", "large_catfish_hoopnet", "bag_seine", "stream_seine", "backpack_electrofishing", "tow_barge_electrofishing"))
# Develop vectors of unique entries
uni.type <- c("North America", "Ecoregion", "State/Province")
uni.area <- sort(unique(metrics$area))
uni.spp <- sort(unique(metrics$common_name))
uni.method <- sort(unique(metrics$method))
uni.watertype <- sort(unique(metrics$waterbody_type))
uni.metric <- c("Length Frequency", "Relative Weight", "CPUE")
# Read in ecoregions shapefiles
ecoregions <- read_sf("ecoregions1/NA_CEC_Eco_Level1.shp")
ecoregions_crs <- "+proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"
ecoregions_trans <- ecoregions %>%
rmapshaper::ms_simplify() %>%
st_set_crs(ecoregions_crs) %>%
st_transform("+proj=longlat +datum=WGS84")
# Read in lat/longs
# Lat/longs are the locations of sampling sites for datasets included in the summary metrics.
# They are used for the plot on the "Explore" page of the app and otherwise do not affect functionality.
# They are not included in this repo for data privacy reasons.
# To get the app to run, read in the `toy_locs.csv` file to populate this data object with fake data.
# # Read in lat/longs
locs <-
read_csv("sites.csv") %>%
# read_csv("toy_locs.csv") %>%
select(-date) # not parseable as is
# Read in example user upload data
ex <- read_csv("example_user_upload_data.csv")
# Create a "not in" function
`%nin%` <- negate(`%in%`)
#Shiny App
ui <- navbarPage(title = "AFS Standard Sampling App",
theme = bslib::bs_theme(bootswatch = "sandstone"),
tabPanel("About",
wellPanel(
tags$head(tags$style(
type="text/css",
"#pics img {display: block; margin-left: auto; margin-right: auto; max-height: 90%; height: 90%; max-width: 100%, width: auto}"
)),
imageOutput("pics"),
h2("About Standard Sampling", align = "center"),
h4("Standardization of sampling methods allows fisheries professionals to compare data across large spatial and temporal scales, encourages data sharing and improves communication.
In light of these benefits, the American Fisheries Society published the first edition of Standard Methods for Sampling North American Freshwater Fishes in 2009.
A new edition of these methods was published September 2024.
The goals of this project were to:"),
br(),
h4("(1) recommend standardized freshwater fish sampling methods for North America, and"),
h4("(2) provide an online database of fish data collected using AFS recommended standard methods where data from individual water bodies could be compared to existing rangewide, ecoregion, and state standards."),
br(),
h4("Since publication, numerous fisheries professionals have adopted the standard methods and many have noted the database as an important tool in management.
The database allows for comparison of fish metrics commonly used in management to assess population health including growth, condition, length-frequency, and catch per unit effort data collected using standard methods.
When developing version two of the database, we examined the strengths and weaknesses of methods used for requesting, analyzing, and displaying data in an online format.
We used this information to achieve our goals of maximizing use and providing simple means to update this program for comparison of fisheries data."),
br(),
h4("We hope that these methods can be adopted by others, particularly those in data-poor regions, to maximize the ability to compare data. "),
h2("Details About App Usage", align = "center"),
h4("Here, you can compare your data from an individual water body,", strong("collected using a standard AFS method"), "to averages across the range of the species, ecoregion, and statewide. This tool will help you assess if fish you have collected are high, average or low for the metric in question."),
h4("We collected thousands of data sets on fishes from across Canada, the United States, and some from Mexico to build comparison summaries. A ", strong("data set (", .noWS = "after"), em("N"), strong(")", .noWS = "before"), " is defined as data collected with AFS standard gears and methods during routine monitoring programs of an entire fish community or a population of specific fish ", strong("in a single waterbody conducted once during a year"), ". For example, data collected from Bass Lake (a small standing water body) sampled by boat electrofishing for Largemouth Bass in 2014 would represent 1 data set. In some cases, data sets included multi-day surveys of the same waterbody (e.g., large reservoirs) where the effort was summed across all sampling days. This excludes surveys targeting specific size groups or those with other biases (e.g., egg counts, juveniles fish surveys)."),
h4("You will see the following tabs in the bar at the top of the page: "),
br(),
h4("- ", strong("About", .noWS = "outside"), ": gives an overview about the standard sampling webtool"),
h4("- ", strong("Explore", .noWS = "outside"), ": displays desired subsets of the standard data in a map and a table"),
h4("- ", strong("View", .noWS = "outside"), ": displays desired subsets of the standard data in graphical form"),
h4("- ", strong("Compare Your Data", .noWS = "outside"), ": allows you to compare your data from a waterbody to standard data in rangewide, ecoregion, or state summaries"),
br(),
h4("Most of the app components can be translated into another language by going to ",
a("Google Translate", href="https://translate.google.com/?sl=auto&tl=en&op=websites", .noWS = "outside"),
" and entering the URL for the app, then selecting the desired language. Maps and plot can only currently be generated using the original version of the app. "),
br(),
h4(strong("If you would like the text of the app bigger, you can increase the font size by hitting the control and plus (+) keys on Windows, or command and plus (+) keys on Macs.")),
br(),
h2("Moving Forward", align = "center"),
h4("These data sets were collected and compiled by ",
a("Scott Bonar's lab", href="https://azcfwru.wixsite.com/azcfwru", .noWS = "outside"),
". Only summaries can be shared. Individual data sets cannot be shared with others because of legal restrictions on their use. As funding permits, additional data will be added to this app, including for more collection methods."),
h4("All feedback on this app is greatly appreciated, and can be provided by sending an email to ",
a("Dr. Bonar", href="mailto:SBonar@ag.arizona.edu", .noWS = "outside"),
" or by submitting an ",
a("issue", href="https://github.com/cct-datascience/AFS_database_code/issues", .noWS = "outside"),
" through the project's ",
a("GitHub repository", href="https://github.com/cct-datascience/AFS_database_code", .noWS = "outside"),
", which is also where the code is located."),
h4("Developed in collaboration with the University of Arizona ",
a("CCT Data Science", href="https://datascience.cct.arizona.edu/"), "team."),
h4 ("Sponsored by:"),
imageOutput("logo")
)
),
tabPanel(title = "Explore",
sidebarLayout(
sidebarPanel(
"Welcome to the American Fisheries Society Standard Sampling Database App!",
br(),
br(),
"To explore standard fish data, select one or more options from each menu below.",
radioGroupButtons(inputId = "typechoice",
label = "Show data by:",
choices = uni.type,
direction = "vertical",
selected = "North America"),
uiOutput("dyn_area"),
selectInput(inputId = "sppchoice",
label = "Select species:",
choices = c("All", uni.spp),
multiple = TRUE,
selected = 'Bluegill'),
selectInput(inputId = "methodchoice",
label = "Select method(s):",
choices = c("All", uni.method),
multiple = TRUE,
selected = "boat_electrofishing"),
selectInput(inputId = "watertypechoice",
label = "Select waterbody type(s):",
choices = c("All", uni.watertype),
multiple = TRUE,
selected = "large_standing_waters"),
selectInput(inputId = "metricchoice",
label = "Select metric(s):",
choices = uni.metric,
multiple = TRUE,
selected = uni.metric),
downloadButton("filterdownload", "Download filtered"),
downloadButton("alldownload", "Download all")
),
mainPanel(
tabsetPanel(
tabPanel("Map",
br(),
h6("Points show approximate locations of data, and colored areas indicate",
strong("EPA Ecoregions Level I"),
". Display name of ecoregion at a location by clicking on map. See more details on the ",
a("EPA website", href="https://www.epa.gov/eco-research/ecoregions-north-america", .noWS = "outside"),
"."),
br(),
leafletOutput("plotSites",
width = 700,
height = 500),
textOutput("report_absent1"),
textOutput("report_absent2")),
tabPanel("Table",
DTOutput("filtertable"))
)
)
)
),
tabPanel(title = "View",
sidebarLayout(
sidebarPanel(
"Welcome to the American Fisheries Society Standard Sampling Database App!",
br(),
br(),
"To view plots of standard fish data, select one option from each menu below.",
radioGroupButtons(inputId = "typechoice2",
label = "Show data by:",
choices = uni.type,
direction = "vertical",
selected = "North America"),
uiOutput("dyn_area2"),
selectInput(inputId = "sppchoice2",
label = "Select species:",
choices = uni.spp,
selected ='Bluegill'),
selectInput(inputId = "methodchoice2",
label = "Select method:",
choices = uni.method,
selected = "boat_electrofishing"),
selectInput(inputId = "watertypechoice2",
label = "Select waterbody type:",
choices = uni.watertype,
selected = "large_standing_waters")
),
mainPanel(plotDownloadUI("LF_plot"),
p("Proportional size distribution length frequency. Black lines indicate standard error."),
hr(),
plotDownloadUI("RW_plot"),
p("Relative weight by proportional size distribution categories. Points indicate means and lines indicate standard error."),
hr(),
plotDownloadUI("CPUE_plot", height = "200px"),
p("Catch per unit effort. The box represents the middle 50% of the standard data with the median value indicated by the line inside. The whiskers extend to the smallest and largest values within 1.5 times the inter quartile range and any individual points outside are outliers. CPUE units depend on collection method: boat and raft electrofishing are fish per hour, gill net is fish per net nights, drifting trammel net is fish per 100-m drift, large catfish hoopnet is fish per 24 hour set, bag seine is fish per 0.25 arc (small standing waters) or 0.5 arc (rivers), stream seine is fish per 10-15m haul, and backpack and tow barge electrofishing are fish per 100m².")
)
)
),
tabPanel(title = "Compare Your Data",
sidebarLayout(
sidebarPanel(
"Welcome to the American Fisheries Society Standard Sampling Database App!",
br(),
br(),
"Upload your fish data for comparison here: ",
fileInput("upload", NULL,
buttonLabel = "upload",
multiple = FALSE,
accept = (".csv"),
placeholder = ""),
"To view plots of standard fish data, select one option from each menu below.",
uiOutput("dyn_type"),
uiOutput("dyn_area3"),
uiOutput("dyn_spp3"),
uiOutput("dyn_method3"),
uiOutput("dyn_watertype3"),
downloadButton("filterdownloaduu", "Download plot data")
),
mainPanel(
tabsetPanel(
tabPanel("Instructions",
uiOutput("instructions"),
DTOutput("example")),
tabPanel("Comparisons",
br(),
h6("If no plots are displayed, upload a dataset to generate comparison plots."),
br(),
plotDownloadUI("LF_plot_UU"),
p("Proportional size distribution length frequency. Black lines indicate standard error."),
hr(),
plotDownloadUI("RW_plot_UU"),
p("Relative weight by proportional size distribution categories. Points indicate means and lines indicate standard error."),
hr(),
plotDownloadUI("CPUE_plot_UU", height = "200px"),
p("Catch per unit effort. The box represents the middle 50% of the standard data with the median value indicated by the line inside. The whiskers extend to the smallest and largest values within 1.5 times the inter quartile range and any individual points outside are outliers. The dashed line represents CPUE for the waterbody. CPUE units depend on collection method: boat and raft electrofishing are fish per hour, gill net is fish per net nights, drifting trammel net is fish per 100-m drift, large catfish hoopnet is fish per 24 hour set, bag seine is fish per 0.25 arc (small standing waters) or 0.5 arc (rivers), stream seine is fish per 10-15m haul, and backpack and tow barge electrofishing are fish per 100m²."))
)
)
),
),
bslib::nav_item(tags$a(
tags$img(src='AFS_logo.png', style="background-color:white;"),
href = "https://fisheries.org/",
style='position:absolute;right:10px;bottom:5px;'
))
)
server <- function(input, output) {
output$pics <- renderImage({
list(
src = file.path("www/fish_circles2.png"),
contentType = "image/png",
height = 365,
width = 819
)
}, deleteFile = FALSE)
output$logo <- renderImage({
list(
src = file.path("www/Standardsamplingsponsors.png"),
contentType = "image/png",
height = 151,
width = 741
)
}, deleteFile = FALSE)
# Render a UI for selecting area depending on North America, Ecoregions, or State/Province
output$dyn_area <- renderUI({
if(input$typechoice == "North America") {
temp <- "North America"
} else if(input$typechoice == "Ecoregion") {
temp <- uni.area[1:12]
} else if(input$typechoice == "State/Province") {
temp2 <- uni.area[uni.area %nin% 'North America']
temp <- temp2[-1:-12]
}
selectInput(inputId = "areachoice",
label = "Select area:",
choices = temp,
selected = temp[1],
multiple = TRUE)
})
# Render a UI for selecting area depending on North America, Ecoregions, or State/Province for tab2
output$dyn_area2 <- renderUI({
if(input$typechoice2 == "North America") {
temp <- "North America"
} else if(input$typechoice2 == "Ecoregion") {
temp <- uni.area[1:12]
} else if(input$typechoice2 == "State/Province") {
temp2 <- uni.area[uni.area %nin% 'North America']
temp <- temp2[-1:-12]
}
selectInput(inputId = "areachoice2",
label = "Select area:",
choices = temp,
selected = temp[1])
})
# Read in raw user upload data to be used in reactive UI's
uu_raw <- reactive({
inFile <- input$upload
uu <- read_csv(inFile$datapath)
invalid_species_names <- uu %>% select(common_name) %>% filter(common_name %nin% unique(metrics$common_name)) %>% pull()
if(any(is.na(uu))){
validate("Uploaded dataset must have no empty rows")
}
# Return informative messages if uu data format is incorrect
validate(
need("state" %in% colnames(uu), "Uploaded dataset is missing state column"),
need("waterbody_name" %in% colnames(uu), "Uploaded dataset is missing waterbody_name column"),
need("common_name" %in% colnames(uu), "Uploaded dataset is missing common_name column"),
need("method" %in% colnames(uu), "Uploaded dataset is missing method column"),
need("year" %in% colnames(uu), "Uploaded dataset is missing year column"),
need(n_distinct(uu$state) == 1, "State column should contain only one state"),
need(n_distinct(uu$waterbody_name) == 1, "Waterbody column should contain only one name"),
need(length(invalid_species_names) == 0, paste0("Species name must match one in the provided list in instructions tab. These names are not valid: ", invalid_species_names))
)
# Duplicate records for all types
uu_state <- uu %>%
select(-one_of("ecoregion")) %>%
mutate(type = "state") %>%
rename(area = state)
if ("ecoregion" %in% names(uu)) {
uu_ecoregion <- uu %>%
select(-state) %>%
mutate(type = "ecoregion") %>%
rename(area = ecoregion)
}
uu_all <- uu %>%
select(-state) %>%
select(-one_of("ecoregion")) %>%
mutate(type = "all", area = "North America")
uu_all <- bind_rows(uu_all, uu_state)
if(exists("uu_ecoregion")) uu_all <- bind_rows(uu_all, uu_ecoregion)
if(exists("uu_state")){
rm(uu_state)
}
if(exists("uu_ecoregion")){
rm(uu_ecoregion)
}
print(uu_all)
})
# Render a UI for selecting area
output$dyn_type <- renderUI({
req(input$upload)
temp <- uu_raw() %>%
select(type) %>%
unique() %>%
mutate(types = case_when(type == "all" ~ "North America",
type == "ecoregion" ~ "Ecoregion",
type == "state" ~ "State/Province")) %>%
slice(match(c("North America", "Ecoregion", "State/Province"), types)) %>%
pull(types)
radioGroupButtons(inputId = "typechoice3",
label = "Show data by:",
choices = temp,
direction = "vertical",
selected = temp[1])
})
# Render a UI for selecting area depending on North America, Ecoregions, or State/Province for tab 3
output$dyn_area3 <- renderUI({
req(input$upload)
if(input$typechoice3 == "North America") {
temp <- "North America"
} else if(input$typechoice3 == "Ecoregion") {
temp <- uu_raw() %>%
filter(type == "ecoregion") %>%
select(area) %>%
unique() %>%
pull()
} else if(input$typechoice3 == "State/Province") {
temp <- uu_raw() %>%
filter(type == "state") %>%
select(area) %>%
unique() %>%
pull()
}
selectInput(inputId = "areachoice3",
label = "Select area:",
choices = temp,
selected = temp[1])
})
# Render a UI for selecting species depending on user upload data in tab 3
output$dyn_spp3 <- renderUI({
req(input$upload)
req(input$areachoice3)
temp <- uu_raw() %>%
filter(area == input$areachoice3) %>%
select(common_name) %>%
unique() %>%
pull()
selectInput(inputId = "sppchoice3",
label = "Select species:",
choices = temp,
selected = temp[1])
})
# Render a UI for selecting species depending on user upload data in tab 3
output$dyn_method3 <- renderUI({
req(input$upload)
req(input$areachoice3)
req(input$sppchoice3)
temp <- uu_raw() %>%
filter(area == input$areachoice3,
common_name == input$sppchoice3) %>%
select(method) %>%
unique() %>%
pull()
selectInput(inputId = "methodchoice3",
label = "Select method:",
choices = temp,
selected = temp[1])
})
# Render a UI for selecting species depending on user upload data in tab 3
output$dyn_watertype3 <- renderUI({
req(input$upload)
req(input$areachoice3)
req(input$sppchoice3)
req(input$methodchoice3)
temp <- uu_raw() %>%
filter(area == input$areachoice3,
common_name == input$sppchoice3,
method == input$methodchoice3) %>%
select(waterbody_type) %>%
unique() %>%
pull()
selectInput(inputId = "watertypechoice3",
label = "Select waterbody type:",
choices = temp,
selected = temp[1])
})
# make filtered, a reactive data object for tab 1 explore, multiple combos okay
filtered <- reactive({
f_df <- metrics %>%
filter(metric %in% input$metricchoice,
area %in% input$areachoice,
case_when("All" %in% input$sppchoice ~ common_name %in% uni.spp,
"All" %nin% input$sppchoice ~ common_name %in% input$sppchoice),
case_when("All" %in% input$methodchoice ~ method %in% uni.method,
"All" %nin% input$methodchoice ~ method %in% input$methodchoice),
case_when("All" %in% input$watertypechoice ~ waterbody_type %in% uni.watertype,
"All" %nin% input$watertypechoice ~ waterbody_type %in% input$watertypechoice)) %>%
arrange(common_name) %>%
select(area, common_name, method, waterbody_type, gcat, metric, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
})
# For downloading the entire dataset for tab 1 explore
all <- reactive({
all_df <- metrics %>%
arrange(common_name) %>%
select(area, common_name, method, waterbody_type, gcat, metric, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
})
output$alldownload <- downloadHandler(
filename = function() {
paste0("AFS-all-", Sys.Date(), ".csv")
},
content = function(file) {
write.csv(all(), file)
}
)
# make locations, a reactive data object for tab 1, only locations that are selected
locate <- reactive({
if(input$typechoice == "North America") {
l_df <- locs %>%
filter(case_when("All" %in% input$sppchoice ~ common_name %in% uni.spp,
"All" %nin% input$sppchoice ~ common_name %in% input$sppchoice),
case_when("All" %in% input$methodchoice ~ method %in% uni.method,
"All" %nin% input$methodchoice ~ method %in% input$methodchoice),
case_when("All" %in% input$watertypechoice ~ waterbody_type %in% uni.watertype,
"All" %nin% input$watertypechoice ~ waterbody_type %in% input$watertypechoice)) %>%
mutate(coords = paste(lat, long)) %>%
group_by(state, ecoregion, waterbody_name, common_name, method,
waterbody_type, coords) %>%
summarize(Nsurveys = n(),
lat = unique(lat),
long = unique(long)) %>%
ungroup()%>%
select(-coords)
} else if(input$typechoice == "Ecoregion") {
l_df <- locs %>%
filter(ecoregion %in% input$areachoice,
case_when("All" %in% input$sppchoice ~ common_name %in% uni.spp,
"All" %nin% input$sppchoice ~ common_name %in% input$sppchoice),
case_when("All" %in% input$methodchoice ~ method %in% uni.method,
"All" %nin% input$methodchoice ~ method %in% input$methodchoice),
case_when("All" %in% input$watertypechoice ~ waterbody_type %in% uni.watertype,
"All" %nin% input$watertypechoice ~ waterbody_type %in% input$watertypechoice)) %>%
mutate(coords = paste(lat, long)) %>%
group_by(state, ecoregion, waterbody_name, common_name, method,
waterbody_type, coords) %>%
summarize(Nsurveys = n(),
lat = unique(lat),
long = unique(long)) %>%
ungroup()%>%
select(-coords)
} else if(input$typechoice == "State/Province") {
l_df <- locs %>%
filter(state %in% input$areachoice,
case_when("All" %in% input$sppchoice ~ common_name %in% uni.spp,
"All" %nin% input$sppchoice ~ common_name %in% input$sppchoice),
case_when("All" %in% input$methodchoice ~ method %in% uni.method,
"All" %nin% input$methodchoice ~ method %in% input$methodchoice),
case_when("All" %in% input$watertypechoice ~ waterbody_type %in% uni.watertype,
"All" %nin% input$watertypechoice ~ waterbody_type %in% input$watertypechoice)) %>%
mutate(coords = paste(lat, long)) %>%
group_by(state, ecoregion, waterbody_name, common_name, method,
waterbody_type, coords) %>%
summarize(Nsurveys = n(),
lat = unique(lat),
long = unique(long)) %>%
ungroup() %>%
select(-coords)
}
})
# Create excluded dataframe for combinations with only one site and one year
exclude <- reactive({
if(input$typechoice == "North America") {
e_df <- locate() %>%
group_by(common_name, method, waterbody_type) %>%
summarize(Nlocs = length(waterbody_name),
Nsurveys_tot = sum(Nsurveys))%>%
filter(Nlocs == 1,
Nsurveys_tot == 1) %>%
select(-Nlocs, -Nsurveys_tot)
} else if(input$typechoice == "Ecoregion") {
e_df <- locate() %>%
group_by(ecoregion, common_name, method, waterbody_type) %>%
summarize(Nlocs = length(waterbody_name),
Nsurveys_tot = sum(Nsurveys))%>%
filter(Nlocs == 1,
Nsurveys_tot == 1) %>%
select(-Nlocs, -Nsurveys_tot)
} else if(input$typechoice == "State/Province") {
e_df <- locate() %>%
group_by(state, common_name, method, waterbody_type) %>%
summarize(Nlocs = length(waterbody_name),
Nsurveys_tot = sum(Nsurveys)) %>%
filter(Nlocs == 1,
Nsurveys_tot == 1) %>%
select(-Nlocs, -Nsurveys_tot)
}
})
# make filtered, a reactive data object for tab 2, single combos only
filtered2 <- reactive({
f_df <- metrics %>%
filter(metric %in% uni.metric,
area %in% input$areachoice2,
common_name %in% input$sppchoice2,
method %in% input$methodchoice2,
waterbody_type %in% input$watertypechoice2) %>%
arrange(common_name) %>%
select(area, common_name, method, waterbody_type, gcat, metric, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
print(f_df)
})
observeEvent(input$areachoice2, {
print(paste0("You have chosen: ", input$areachoice2))
})
output$filterdownload <- downloadHandler(
filename = function() {
paste0("AFS-filtered-", Sys.Date(), ".csv")
},
content = function(file) {
write_csv(filtered(), file)
}
)
# Making the table look nice
output$filtertable <- renderDT({
filtered() %>%
mutate(method = str_replace_all(method, "_", " "),
area = str_replace_all(area, "_", " "),
waterbody_type = str_replace_all(waterbody_type, "_", " ")) %>%
dplyr::mutate(N = as.integer(N),
mean = round(mean, 2),
se = round(se, 2),
`5%` = round(`5%`, 2),
`25%` = round(`25%`, 2),
`50%` = round(`50%`, 2),
`75%` = round(`75%`, 2),
`95%` = round(`95%`, 2)) %>%
dplyr::rename("Area" = area,
"Common Name" = common_name,
"Method" = method,
"Waterbody Type" = waterbody_type,
"Proportional Size Distribution" = gcat,
"Metric" = metric,
"N" = N,
"Mean" = mean,
"SE" = se,
"5%" = `5%`,
"25%" = `25%`,
"50%" = `50%`,
"75%" = `75%`,
"95%" = `95%`)
})
filtered3 <- reactive({
f_df <- metrics %>%
filter(metric %in% uni.metric,
area %in% input$areachoice3,
common_name %in% input$sppchoice3,
method %in% input$methodchoice3,
waterbody_type %in% input$watertypechoice3) %>%
arrange(common_name) %>%
select(area, common_name, method, waterbody_type, gcat, metric, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
})
uu_processed <- reactive({
# Suppresses error messages for plots until inputs are chosen
req(input$areachoice3)
req(input$sppchoice3)
req(input$methodchoice3)
req(input$watertypechoice3)
inFile <- input$upload
uu <- read_csv(inFile$datapath)
print("UU original")
print(uu)
# Duplicate records for all types
uu_state <- uu %>%
select(-one_of("ecoregion")) %>%
mutate(type = "state") %>%
rename(area = state)
if ("ecoregion" %in% names(uu)) {
uu_ecoregion <- uu %>%
select(-state) %>%
mutate(type = "ecoregion") %>%
rename(area = ecoregion)
}
uu_all <- uu %>%
select(-state) %>%
select(-one_of("ecoregion")) %>%
mutate(type = "all", area = "North America")
uu_all <- bind_rows(uu_all, uu_state)
if(exists("uu_ecoregion")) uu_all <- bind_rows(uu_all, uu_ecoregion)
# Calculate 3 metrics for user data
uu_counts <- uu_all %>%
group_by(type, area, common_name, method, waterbody_type) %>%
summarise(N = n())
uu_cpue <- calculate_cpue(uu_all)
uu_lf <- calculate_lf(uu_all)
uu_rw <- calculate_rw(uu_all)
uu_process <- bind_rows(uu_cpue, uu_lf, uu_rw) %>%
left_join(uu_counts, by = c("type", "area", "common_name", "method", "waterbody_type")) %>%
mutate(gcat = case_when(gcat == "stock" ~ "S-Q",
gcat == "quality" ~ "Q-P",
gcat == "preferred" ~ "P-M",
gcat == "memorable" ~ "M-T",
gcat == "trophy" ~ "T") %>%
factor(levels = c("S-Q", "Q-P", "P-M", "M-T", "T")))
f_df <- uu_process %>%
filter(metric %in% uni.metric,
area %in% input$areachoice3,
common_name %in% input$sppchoice3,
method %in% input$methodchoice3,
waterbody_type %in% input$watertypechoice3) %>%
arrange(common_name) %>%
select(area, common_name, method, waterbody_type, gcat, metric, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
print("UU filtered")
print(f_df$metric)
print(f_df, n = Inf)
})
# For downloading the filtered dataset for tab 3 comparison
both <- reactive({
both_df <- uu_processed() %>%
bind_rows(filtered3(), .id = "id") %>%
rename(data_source = id) %>%
mutate(data_source = case_when(data_source == 1 ~ "User upload",
data_source == 2 ~ "Standardized")) %>%
arrange(metric) %>%
select(metric, data_source, area, common_name, method, waterbody_type, gcat, N, mean,
se, `5%`, `25%`, `50%`, `75%`, `95%`)
})
output$filterdownloaduu <- downloadHandler(
filename = function() {
paste0("AFS-UU-filtered-", Sys.Date(), ".csv")
},
content = function(file) {
write.csv(both(), file)
}
)
# Map of ecoregions and sites
output$plotSites <- renderLeaflet({
# Remove 'exclude()' from plot_data if only 1 site or 1 year is represented
plot_data <- locate() %>%
anti_join(exclude())
# print(plot_data)
factpal <- colorFactor(rainbow(length(unique(ecoregions_trans$NA_L1CODE))),
ecoregions_trans$NA_L1CODE)
map <- leaflet() %>%
addTiles(options = tileOptions(minZoom = 2, maxZoom = 6)) %>%
addPolygons(data = ecoregions_trans, color = ~factpal(NA_L1CODE),
fillOpacity = 0.5, popup = ~htmltools::htmlEscape(NA_L1NAME),
stroke = FALSE)
if(nrow(plot_data) > 0) {
map <- map %>%
addCircleMarkers(data = plot_data, lng = ~long, lat = ~lat, stroke = FALSE,
radius = 3, fillOpacity = 0.75, fillColor = "black",
popup = popupTable(plot_data,
zcol = 4:7,
row.numbers = FALSE,
feature.id = FALSE))
}
print(map)
})
# Text to describe insufficient sample size for anonymity
output$report_absent1 <- renderText({
paste0(nrow(exclude()), " site(s) not shown to maintain data anonymity. ")
})
# Text to describe sites missing lat/lon
output$report_absent2 <- renderText({
temp <- locate() %>% filter(is.na(lat))
if(nrow(temp) == 0) {
paste0(nrow(temp),
" site(s) not shown due to unreported coordinates. ")
} else {
paste0(nrow(temp),
" site(s) not shown due to unreported coordinates in ",
paste(unique(temp$state), collapse = ", "),
". ")
}
})
plotLengthFrequency <- reactive({
temp <- filtered2() %>%
filter(metric == "Length Frequency")
N <- temp %>%
distinct(N) %>%
pull(N)
if(nrow(temp) == 0){
fig <- ggplot() +
annotate("text", x = 1, y = 1, size = 8,
label = "No length frequency data for selected options") +
theme_void()
} else {
fig <- ggplot(temp, aes(x = gcat, y = mean)) +
geom_bar(stat = "identity", fill = "black") +
geom_errorbar(aes(ymin = mean - se,
ymax = mean + se),
width = 0) +
scale_y_continuous("Frequency (%)",
limits = c(0, 100),
expand = c(0, 0)) +
theme_classic(base_size = 16) +
xlab("Proportional size distribution categories") +
theme(legend.position = "none") +
geom_richtext(x = 5, y = 90, label = paste0("<i>N</i> = ", N), size = 7, fill = NA, label.color = NA)
}
print(fig)
})
callModule(plotDownload, "LF_plot", plotLengthFrequency)
plotRelativeWeight <- reactive({
temp <- filtered2() %>%
filter(metric == "Relative Weight")
if(nrow(temp) == 0){
fig <- ggplot() +
annotate("text", x = 1, y = 1, size = 8,
label = "No relative weight data for selected options") +
theme_void()
} else {
fig <- ggplot(temp, aes(x = gcat)) +
geom_point(aes(y = mean),
size = 4,
color = "black") +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
width = 0,
color = "black") +
geom_hline(yintercept = 100, linetype = "dashed") +
scale_x_discrete(drop = FALSE) +
ylim(50, 160) +
labs(y = "Relative weight (<i>W<sub>r</sub></i>)") +
theme_classic(base_size = 16) +
xlab("Proportional size distribution categories") +
theme(legend.position = "bottom",
legend.title = element_blank(),
axis.title.y = ggtext::element_markdown())
}
print(fig)
})
callModule(plotDownload, "RW_plot", plotRelativeWeight)
plotCPUE <- reactive({
temp <- filtered2() %>%
filter(metric == "CPUE")
N <- unique(temp$N)
if(nrow(temp) == 0){
fig <- ggplot() +
annotate("text", x = 1, y = 1, size = 8,
label = "No CPUE data for selected options") +
theme_void()
} else {
fig <- ggplot(temp, aes(y = area)) +
geom_boxplot(aes(xmin = `5%`,
xlower = `25%`,
xmiddle = `50%`,
xupper = `75%`,
xmax = `95%`),
stat = "identity",
fill = "white") +
scale_x_continuous("CPUE") +
theme_classic(base_size = 16) +
labs(title = paste0("*N* = ", N)) +
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
plot.title = ggtext::element_markdown(hjust = 1, face = "bold"))
}
print(fig)
})
callModule(plotDownload, "CPUE_plot", plotCPUE)
mtext <- "
<br>
<center><b>How to Format Input Data</b></center>
You can upload your own data to compare to the standardized data. This needs to be provided as a csv file that will have length and/or weight measurements with one row per observation (a single fish or multiple fish summed). This app will calculate the three metrics of interest for each unique combination of area, species, collection method, type of water body, and year. The three metrics are:
1. Catch per unit effort (CPUE)
2. Length frequency
3. Relative weight
<center><b>Column Details</b></center>
Below are the details of the required columns in the data. The order of the columns does not matter <b>BUT</b> the column names are <b>case sensitive and must be lower case</b>. Additionally, only upload data from <b>one</b> waterbody sampling effort at a time (under the column `waterbody_name`). There is an example dataset at the bottom of the page with simulated data that may be a helpful guide.
1. CPUE requires `effort` column
2. Length frequency requires `total_length` column
3. Relative weight requires `weight` and `total_length` columns
Required columns in input dataframe:
- **Location**:
- **Requires** `state` column
- `state` is name of state where fish were collected, spelled out with first letter capitalized
- Every row should be the same state (as it's for the same water body)
- An `ecoregion` column can optionally be included, to compare your data to standardized data in that ecoregion
- `ecoregion` is name of ecoregion where fish were collected, spelled out and capitalized correctly
- You can also find your ecoregion by clicking on your location the map on the Explore tab. Ecoregions can also be determined from [EPA ecoregions](https://www.epa.gov/eco-research/ecoregions-north-america) level 1. Correctly formatted ecoregion names are listed below.
- `waterbody_name` is the name of the water body
<style>
.basic-styling td,
.basic-styling th {
border: 1px solid #999;