-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSETdash.Rmd
2661 lines (2197 loc) · 114 KB
/
SETdash.Rmd
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
---
title: "SET QA/QC Visualizer"
output:
flexdashboard::flex_dashboard:
theme: yeti
orientation: columns
runtime: shiny
---
```{r global, include=FALSE}
### STILL TO FIX
# quantiles
# first col diff from base should not be colored in matrix
# double read fnot size
#
# when metric is changed or metric diff, tell user to refresh
#
# for heatmap diff from first survey error that can't figure out domain
#
# fix the cap_text etc
#
# heatmaps don't have colors (but the legends are fine)
#
# maps not showing
### NOTES
# Converted all tibbles to data frames to get rid of phantom column name errors
### NAMING RULES
# Functions: FuncTest(dat1_there, dat2_here)
# Action buttons: button_PushMe
# User inputs: sel_SelectMe
# Lists, data frames, vectors, variables...: station_files_list, station_df, station_vec, here_is_a_variable
# Data frame cols: df$ColThisOne, df$ColThatOne
# List elements: list$ElementOne, list$ElementTwo
# Reactive elements: rv$ThisOne, rv$ThatOne
# Temporary variables: temp_this_df
# Well panel id's: wp_FilterParkSite
rm(list=ls())
### Load libraries -----
# Will automatically install any libraries it can't find (except flexdashboard)
pkgs <- c(
"flexdashboard",
"shiny",
"knitr",
"odbc", # pull data from SQL server
"scales",
"leaflet",
"RgoogleMaps", # for mapzoom
"plotly",
"tidyverse",
"plyr",
"readr",
"magrittr",
"leaflet.extras",
"lubridate",
"here",
"httr", # use web services
"sf", # replace rgdal
"sp", # transform projections
"purrr", # for applying functions to dplyr groups
"shinyFiles", # for user to save files in specified location
"RColorBrewer", # to display brewer palettes
"stringr", # to detect text snippets
"shinyBS", # tooltips for inputs
"reactable",
"data.table", # for fast lag calcs
"DT", # for interactive tables
"zoo", # for year-month and carry-forward NA's for lag
"cowplot", # to get legends from plots
"shinyWidgets", # for radiogroup buttons
"gridExtra", # for arranging plots and adding plot annotations (ggplotly can't do captions or subtitles)
"stars",
"ggpubr",
"RgoogleMaps", # for MaxZoom & MinZoom
"leaflet.minicharts") # for pie charts in leaflet maps
installed_pkgs <- pkgs %in% installed.packages()
if (length(pkgs[!installed_pkgs]) > 0) install.packages(pkgs[!installed_pkgs], repos = "https://cloud.r-project.org" , dep=TRUE)
lapply(pkgs, library, character.only = TRUE)
options(shiny.maxRequestSize = 20*1024^2,
timeout = 300,
stringsAsFactors = FALSE,
DT.options = list(
hover = TRUE,
scrollX = TRUE,
scrollY = TRUE,
autoWidth = FALSE),
# Header width doesn't match body width when this is set to TRUE. To fix, would need to include code to recalculate widths only after a tab is visible. If setting column widths, need to set autoWidth to TRUE
dplyr.summarise.inform = FALSE
)
```
```{r startup}
rv <- reactiveValues(DataSET = NULL, DataStation = NULL, DataEvent = NULL, DataCriticalInfo = NULL, DataMarker = NULL, UnitPoly = NULL, SubDataSET = NULL, SubDataSummary = NULL, SubDataDateSummary = NULL, SubDataMarker = NULL, SubDataMarkerSummary = NULL, SubDataDateMarkerSummary = NULL, PlotData = NULL, ShowDM = FALSE, PinHeatDataSET = NULL, ThreshCounts = NULL, sel_PinSite = NULL, sel_SETmetric = NULL, sel_DiffFromBase = NULL, sel_ThresholdType = NULL, ThreshLevels = NULL, sel_YrRange = NULL, PinHeatPlots = NULL, PinPieMatrix = NULL, sel_MHSite = NULL, MarkerHeatDataSET = NULL, RawMHHeatPlots = NULL, MapDat = NULL, DataSET_NERRs = NULL)
level_colors = c("#ffd700", "#add8e6", "#ffa500", "#ffffff") # corresponds with low, middle, high, NA
```
```{r css}
# Validation messages are red
tags$style(".shiny-output-error-validation {
font-size:14px;
color: #FF0000;
}") # validation text is in red. Could also add 'font-weight: bold;'
# This allows renderTables to scroll when overflow
tags$style(".chart-wrapper {
overflow-x:scroll;
overflow-y:scroll;
}")
tags$style("table.dataTable tbody th, table.dataTable tbody td input.form-control {
padding: 2px 5px;
}") # reduce padding in data tables
tag.map.title <- tags$style(HTML("
.leaflet-control.map-title {
transform: translate(-50%,20%);
position: fixed !important;
left: 50%;
text-align: center;
padding-left: 10px;
padding-right: 10px;
background: rgba(255,255,255,0.75);
font-weight: bold;
font-size: 28px;
}
")) # add title to leaflet map
# Show data tables at full height
tags$style(".datatables.html-widget.html-widget-static-bound {
height: auto !important;
width: 90vw !important;
}")
tags$style(".dataTables_scrollBody {
height: unset !important;
}")
```
```{r functions}
### FUNCTIONS ----
## Reactable Functions
# Reactable bar chart function
bar_chart <- function(label, width = "100%", height = "14px", fill = "#00bfc4", background = NULL) {
bar <- div(style = list(background = fill, width = width, height = height))
chart <- div(style = list(flexGrow = 1, marginLeft = "6px", background = background), bar)
div(style = list(display = "flex", alignItems = "center"), label, chart)
}
# Reactable tooltip formatting
with_tooltip <- function(value, tooltip) {
tags$abbr(style = "text-decoration: underline; text-decoration-style: dotted; cursor: help", title = tooltip, value)
}
## Other Functions
FuncAllNoneButtons <- function(cond, name_all, name_none) {
# Function to create 'Select All' and 'Select None' action buttons
#
# Args:
# cond: The input ID that needs to be defined for buttons to show (enter as input.XXX rather than as input$XXX)
# name_all: ID to assign to 'Select All' button
# name_none: ID to assign to 'Select None' button
#
conditionalPanel(
condition = paste0("typeof ", cond, " !== 'undefined'"),
actionButton(name_all, "Select All", style="color:black; display:inline-block; border:1px; padding:4px 12px;"),
actionButton(name_none, "Select None", style="color:black; display:inline-block; border:1px; padding:4px 12px;")
)
}
FuncParkBoundaries <- function(park_vec) {
# Function to get park unit boundaries from IRMA
#
# Args:
# park_vec: Vector of 4-letter park codes for which boundaries should be obtained
#
# Returns:
# A data frame with additional columns classifying survey date by week, month, year
unitBoundaryURL <- paste0("https://services1.arcgis.com/fBc8EJBxQRMcHlei/ArcGIS/rest/services/IMD_Units_Generic_areas_of_analysis_(AOAs)_-_IMD_BND_ALL_UNITS_AOA_nad_py_view/FeatureServer/1/query?where=UNITCODE+%3D+%27, park_vec, %27&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=0.0&units=esriSRUnit_Meter&returnGeodetic=false&outFields=*&returnGeometry=true&returnCentroid=false&featureEncoding=esriDefault&multipatchOption=xyFootprint&maxAllowableOffset=&geometryPrecision=&outSR=&defaultSR=&datumTransformation=&applyVCSProjection=false&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnQueryGeometry=false&returnDistinctValues=false&cacheHint=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&having=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&returnExceededLimitFeatures=true&quantizationParameters=&sqlFormat=none&f=pgeojson&token=") # save output as WGS84
if(httr::http_status(GET(unitBoundaryURL))$category!="Success") { # if not a valid service call or if the web service is down, abort
showModal(
urlModal(unitBoundaryURL, title = "Data Retrieval Error", subtitle = paste0("Error retrieving park_name unit boundary data from IRMA. The message from the web service is: `", http_status(GET(unitBoundaryURL))$message, "`.\n\nTo confirm this is a problem with the web service (and not the dashboard), enter the above URL in a browser and see if data successfully downloads. If an error results, email IRMA support ([email protected]) for assistance."))
)
}
shiny::req(httr::http_status(GET(unitBoundaryURL))$category=="Success")
tempUnitOutput <- "tempUnit.geojson"
# download.file(unitBoundaryURL, tempUnitOutput) # readOGR geoJSON driver needs dsn to be a local file, so download the file first, then read it
# st_read("path_to_file.shp", promote_to_multi = FALSE)
# https://r-spatial.org/r/2022/04/12/evolution.html
imported_dat <- tryCatch(sf::read_sf(tempUnitOutput, stringsAsFactors = TRUE), error=function(e) print("Error retrieving data")) # return error message if problems still arise with downloading from web services
if(class(imported_dat)!="SpatialPolygonsDataFrame") {
showModal(
urlModal(unitBoundaryURL, title = "Data Retrieval Error", subtitle = paste0("Could not successfully retrieve park_name unit boundary data from IRMA. To see if this is a problem with the web service (and not the dashboard), enter the above URL in a browser and see if data successfully downloads with boundary information in geojson format. If necessary, email IRMA support ([email protected]) for assistance."))
)
}
shiny::req(class(imported_dat)=="SpatialPolygonsDataFrame")
imported_dat <- sf::st_transform(imported_dat, sp::CRS("+proj=longlat +datum=WGS84")) # convert to WGS84
rv$UnitPoly <- imported_dat
rm(imported_dat)
}
FuncCalcChange <- function(dat) {
# Function to calculate change per year for pin height
#
# Args:
# dat: A final pin data frame
#
# Returns:
# A data frame with an additional column calculating change in SET height (observation_type == "Standard". When prior or first (whichever is selected) survey is NA, will give NA.
#
dt1 <- dat %>%
dplyr::filter(observation_type == "Standard") %>%
dplyr::select(record_ID, park_code, site_name, station_name, station_code, SET_direction_azimuth, pin_position, event_date_UTC, pin_height_mm, standardized_soil_elev_mm, soil_elev_m, SET_reader, SET_instrument, pin_collection) %>%
dplyr::arrange(event_date_UTC)
dt2 = data.table(dt1 %>% dplyr::select(-record_ID))
dt2[, c("event_date_UTC_lag", "pin_height_mm_lag", "standardized_soil_elev_mm_lag", "soil_elev_m_lag", "SET_reader_lag", "SET_instrument_lag", "pin_collection_lag") := shift(.SD, 1), by=c("park_code", "site_name", "station_name", "station_code", "SET_direction_azimuth", "pin_position")] # lag calculations
dt3 <- dplyr::bind_cols(dt1["record_ID"], as.data.frame(dt2)) %>%
dplyr::select(record_ID, event_date_UTC_lag, pin_height_mm_lag, standardized_soil_elev_mm_lag, soil_elev_m_lag, SET_reader_lag, SET_instrument_lag, pin_collection_lag) %>%
dplyr::right_join(dat, by = "record_ID") %>%
dplyr::mutate(
diff_pin_height_mm = pin_height_mm - pin_height_mm_lag,
diff_standardized_soil_elev_mm = standardized_soil_elev_mm - standardized_soil_elev_mm_lag,
diff_soil_elev_m = round(soil_elev_m - soil_elev_m_lag, 3),
diff_days = event_date_UTC - event_date_UTC_lag,
SET_reader_change = SET_reader!=SET_reader_lag,
SET_reader_transition = ifelse(SET_reader_change, paste0("[", event_date_UTC_lag, "] ", SET_reader_lag, " -->", " [", event_date_UTC, "] ", SET_reader), NA),
SET_instrument_change = SET_instrument!=SET_instrument_lag,
SET_instrument_transition = ifelse(SET_instrument_change, paste0("[", event_date_UTC_lag, "] ", SET_instrument_lag, " -->", " [", event_date_UTC, "] ", SET_instrument), NA),
pin_collection_change = pin_collection!=pin_collection_lag,
pin_collection_transition = ifelse(pin_collection_change, paste0("[", event_date_UTC_lag, "] ", pin_collection_lag, " -->", " [", event_date_UTC, "] ", pin_collection), NA),) %>%
dplyr::select(-event_date_UTC_lag, -pin_height_mm_lag, -standardized_soil_elev_mm_lag, -soil_elev_m_lag, -SET_reader_lag, -SET_instrument_lag, -pin_collection_lag) %>%
dplyr::ungroup()
# Calculate differences from initial survey event
init_surveys <- dt1 %>%
dplyr::group_by(park_code, site_name, station_name, station_code) %>%
slice_min(order_by = event_date_UTC) %>%
dplyr::select(park_code, site_name, station_name, station_code, SET_direction_azimuth, pin_position, first_event_date_UTC = event_date_UTC, first_pin_height_mm = pin_height_mm, first_standardized_soil_elev_mm = standardized_soil_elev_mm, first_soil_elev_m = soil_elev_m)
dt3 %<>%
dplyr::left_join(init_surveys, by = c("park_code", "site_name", "station_name", "station_code", "SET_direction_azimuth", "pin_position")) %>%
dplyr::mutate(
base_diff_pin_height_mm = pin_height_mm - first_pin_height_mm,
base_diff_standardized_soil_elev_mm = standardized_soil_elev_mm - first_standardized_soil_elev_mm,
base_diff_soil_elev_m = round(soil_elev_m - first_soil_elev_m, 3),
diff_days_base = event_date_UTC - first_event_date_UTC
)
dt3$base_diff_pin_height_mm[dt3$diff_days_base == 0] <- NA
dt3$base_diff_standardized_soil_elev_mm[dt3$diff_days_base == 0] <- NA
dt3$base_diff_soil_elev_m[dt3$diff_days_base == 0] <- NA
return(dt3)
}
FuncCalcPinAlert <- function(dat, event_level_dat) {
# Function to classify pin_height_mm by user-specified alert settings
#
# Args:
# dat: A filtered SET data frame for the selected site
# event_level_dat: Event and critical information data for the corresponding site and survey date
#
# Returns:
# A data frame with an additional columns level for heatmap color-coding
#
dat2 <- dat %>%
dplyr::mutate(
sel_metric = get(rv$sel_SETmetric),
sel_diff_metric = get(paste(rv$sel_DiffFromBase, rv$sel_SETmetric, sep = "_"))
)
double_dat <- dat2 %>% # Double reads only, need to merge it back--hopefully there is never more than one double read of a pin in a survey!
dplyr::filter(observation_type == "Double Read") %>%
dplyr::select(station_name, event_date_UTC, SET_direction_azimuth, SET_direction, pin_position, double_read_type, SET_reader2 = SET_reader, sel_metric2 = sel_metric)
dat2_standard <- dat2 %>%
dplyr::filter(observation_type == "Standard") %>%
dplyr::left_join(double_dat, by = c("station_name", "event_date_UTC", "SET_direction_azimuth", "SET_direction", "pin_position")) %>%
dplyr::left_join(event_level_dat, by = c("station_name", "event_date_UTC")) %>%
dplyr::mutate(
dpl_alert = if("dpl_alert" %in% input$sel_PinAlerts) {ifelse(dpl != "Accepted", TRUE, FALSE)} else {FALSE},
pin_flag_alert = if("pin_flag_alert" %in% input$sel_PinAlerts) { ifelse(!is.na(pin_flag_label)|!is.na(pin_flag_notes), TRUE, FALSE)} else {FALSE},
veg_notes_alert = if("veg_notes_alert" %in% input$sel_PinAlerts) { ifelse(!is.na(vegetation_notes), TRUE, FALSE)} else {FALSE},
SET_notes_alert = if("SET_notes_alert" %in% input$sel_PinAlerts) { ifelse(!is.na(SET_notes), TRUE, FALSE)} else {FALSE},
analysis_alert = if("analysis_alert" %in% input$sel_PinAlerts) { ifelse(!is.na(exclude_int_reason_ID)|!is.na(exclude_int_reason)| !is.na(exclude_cumul_reason_ID)|!is.na(exclude_cumul_reason), TRUE, FALSE)} else {FALSE},
SET_reader_alert = if("SET_reader_alert" %in% input$sel_PinAlerts) {ifelse(SET_reader_change==TRUE, TRUE, FALSE)} else {FALSE},
SET_instrument_alert = if("SET_instrument_alert" %in% input$sel_PinAlerts) {ifelse(SET_instrument_change==TRUE, TRUE, FALSE)} else {FALSE},
pin_collection_alert = if("pin_collection_alert" %in% input$sel_PinAlerts) {ifelse(pin_collection_change==TRUE, TRUE, FALSE)} else {FALSE},
event_notes_alert = if("event_notes_alert" %in% input$sel_PinAlerts) {
ifelse(!is.na(event_notes), TRUE, FALSE)} else {FALSE}) %>%
rowwise() %>%
dplyr::mutate(
alert_level = any(dpl_alert, pin_flag_alert, veg_notes_alert, SET_notes_alert, analysis_alert, SET_reader_alert, SET_instrument_alert, pin_collection_alert, event_notes_alert), # TRUE if any requested alert is TRUE
border_color = ifelse(alert_level, "#FF0000", NA) # colored border for an alert
)
return(dat2_standard)
}
FuncLevelNames <- function(type, low, high) {
# Function to create the vector of level names corresponding with threshold colors
#
# Args:
# type: "numb" or "quant" for threshold type
# low, high: lower cutoff, upper cutoff
#
# Returns:
# Character vector of level names
if(type == "quant") {
nam <- c(
paste0("lowest quantile (< ", input$sel_QuantileLower, " quantile)"),
"middle quantile",
paste0("highest quantile (>= ", input$sel_QuantileUpper, " quantile)"),
"N/A"
)
}
if(type == "numb") {
nam <- c(
paste0("big decline (< ", input$sel_ThresholdLower, "mm)"),
"within expected range",
paste0("big increase (>= ", input$sel_ThresholdUpper, "mm)"),
"N/A"
)
}
return(nam)
}
FuncCalcQuant <- function(dat) {
# Function to classify diff_pin_height_mm by user-specified groups and quantiles
#
# Args:
# dat: A filtered SET data frame for the selected site
#
# Returns:
# A data frame with an additional columns classifying diff_pin_height_mm relative to specified quantiles per group
#
dat <- droplevels(dat)
dat %<>% dplyr::mutate(
GroupingVar = switch(input$sel_QuantileGroup,
"site" = site_name,
"station" = station_name))
quant_list <- dat %>%
dplyr::group_by(GroupingVar) %>%
group_map(~ quantile(.x$sel_diff_metric, probs = c(input$sel_QuantileLower, input$sel_QuantileUpper), na.rm = TRUE))
quant_df <- data.frame(do.call("rbind", quant_list))
names(quant_df) <- c("lower_cutoff", "upper_cutoff")
quant_df$GroupingVar <- levels(dat$GroupingVar)
dat2 <- dat %>%
dplyr::left_join(quant_df, by = "GroupingVar") %>%
dplyr::mutate(level = NA)
dat2$level <- ifelse(
dat2$sel_diff_metric < dat2$lower_cutoff, "low", ifelse(
dat2$sel_diff_metric > dat2$upper_cutoff, "high", "middle"))
dat2$GroupingVar <- NULL
return(dat2)
}
FuncCalcThresh <- function(dat) {
# Function to classify SET change by user-specified numeric thresholds
#
# Args:
# dat: A filtered SET data frame for the specified site
#
# Returns:
# A data frame with an additional column classifying diff_pin_height_mm relative to specified thresholds
#
dat <- droplevels(dat)
dat2 <- dat
dat2$lower_cutoff <- input$sel_ThresholdLower
dat2$upper_cutoff <- input$sel_ThresholdUpper
dat2$level = NA
dat2$level <- ifelse(
dat2$sel_diff_metric < dat2$lower_cutoff, "low", ifelse(
dat2$sel_diff_metric > dat2$upper_cutoff, "high", "middle"))
return(dat2)
}
FuncCalcMH <- function(dat) {
# Function to calculate MH change
#
# Args:
# dat: Marker horizon data frame
#
# Returns:
# A data frame with additional columns calculating MH average and identifying event changes
#
dt1 <- dat %>%
dplyr::select(record_ID, park_code, station_name, marker_horizon_name, core_measurement_number, event_date_UTC, core_measurement_depth_mm, reader_name) %>%
dplyr::arrange(event_date_UTC)
dt2 = data.table(dt1 %>% dplyr::select(-record_ID))
dt2[, c("event_date_UTC_lag", "core_measurement_depth_mm_lag", "reader_name_lag") := shift(.SD, 1), by=c("park_code", "station_name", "marker_horizon_name", "core_measurement_number")]
dt3 <- dplyr::bind_cols(dt1["record_ID"], as.data.frame(dt2)) %>%
dplyr::select(record_ID, event_date_UTC_lag, core_measurement_depth_mm_lag, reader_name_lag) %>%
dplyr::right_join(dat, by = "record_ID") %>%
dplyr::mutate(
diff_depth_mm = core_measurement_depth_mm - core_measurement_depth_mm_lag,
diff_days = event_date_UTC - event_date_UTC_lag,
reader_change = reader_name!=reader_name_lag,
reader_transition = ifelse(reader_change, paste0("[", event_date_UTC_lag, "] ", reader_name_lag, " -->", " [", event_date_UTC, "] ", reader_name), NA)) %>%
dplyr::select(-event_date_UTC_lag, -core_measurement_depth_mm_lag, -reader_name_lag) %>%
dplyr::ungroup()
return(dt3)
}
FuncCalcMHAlert <- function(dat) {
# Function to classify core_measurement_depth_mm by user-specified alert settings
#
# Args:
# dat: A filtered MH data frame for the selected site
#
# Returns:
# A data frame with an additional columns level for heatmap color-coding
#
# shiny::req(!is.null(input$sel_MHAlerts), !is.null(input$sel_MHReaderAlert))
# For a particular station, find out all MH survey dates and create template so NULL values are appropriately entered
template <- dat %>%
droplevels() %>%
dplyr::select(network_code, network_name, park_code, park_name, site_name, station_code, station_name, marker_horizon_name, core_measurement_number, established_date, retired_date) %>%
distinct()
all_dates <- dat %>%
droplevels() %>%
dplyr::select(event_date_UTC, event_date_yr, event_date_mnth, event_date_wk) %>%
distinct()
dat2 <- merge(template, all_dates) %>%
dplyr::left_join(dat) %>%
dplyr::mutate(
dpl_alert = if("dpl_alert" %in% input$sel_MHAlerts) {ifelse(dpl != "Accepted", TRUE, FALSE)} else {FALSE},
core_condition_alert = if("core_condition_alert" %in% input$sel_MHAlerts) {ifelse(!core_condition %in% c("Excellent", "Good") & !is.na(core_condition), TRUE, FALSE)} else {FALSE},
core_notes_alert = if("core_notes_alert" %in% input$sel_MHAlerts) { ifelse(!is.na(core_notes), TRUE, FALSE)} else {FALSE},
core_event_notes_alert = if("core_event_notes_alert" %in% input$sel_MHAlerts) {ifelse(!is.na(core_event_notes), TRUE, FALSE)} else {FALSE},
reader_change_alert = if(input$sel_MHReaderAlert) {
ifelse(reader_change==TRUE, TRUE, FALSE)} else {FALSE},
border_color = ifelse(reader_change_alert==TRUE, "#FF0000", NA), # colored border for reader change alert
level = case_when(
dpl_alert|core_condition_alert|core_notes_alert|core_event_notes_alert ~ "MH_alert",
TRUE ~ "no_alert") # Cell color is yellow if any alert
)
return(dat2)
}
FuncSubplotMargins <- function(tot_page, num_subplots, left_prop = 0, right_prop = 0, top_prop = 0.1, bottom_prop = 0.1) {
adj_top = ifelse(tot_page > 400, top_prop/num_subplots, .045) # need to divide so as number of plots increases, the space between plots doesn't get huge
adj_bottom = ifelse(tot_page > 400, bottom_prop/num_subplots, .045)
marg_lost <- adj_top + adj_bottom
indiv <- 1/num_subplots
temp_rel_hts <- c(indiv-marg_lost, rep(indiv, num_subplots - 2), indiv-marg_lost)
rel_hts <- temp_rel_hts/sum(temp_rel_hts)
marg <- c(left_prop, right_prop, adj_top, adj_bottom)
return_list <- list(hts = rel_hts, marg = marg)
return(return_list)
}
FuncPlotlyMHHeatPlot <- function(dat, heat_metric, discrete_cols, discrete_levels) {
# Function to create plotly heatmaps of raw MH data
#
# Args:
# dat: A filtered MH data frame with raw depth data for a single site
# heat_metric: "raw" for raw MH data
# discrete_cols: For discrete fill, the vector of colors
# discrete_levels: For discrete fill, the levels corresponding with colors
#
# Returns:
# GGplot heat map
#
withProgress(message = "Just a moment", value = 0, {
keep_dates <- dat %>%
dplyr::filter(!is.na(core_measurement_depth_mm)) %>%
distinct(event_date_UTC) %>%
pull(.)
subdat <- dat %>%
ungroup() %>%
dplyr::filter(event_date_UTC %in% keep_dates) %>%
dplyr::arrange(station_code, marker_horizon_name, core_measurement_number, event_date_UTC) %>%
dplyr::mutate(hover_label = paste0("<span style='font-size:16px; font-weight:bold;'>", "MH Name: ", marker_horizon_name, "</span><br>Core #: ", core_measurement_number, "<br>Visit Date: ", event_date_UTC, "<br>Core Depth (mm): ", core_measurement_depth_mm, "<br>Core Type: ", core_type, "<br>Date Est'd: ", established_date, "<br>Core Condition: ", core_condition, "<br>Core Notes: ", core_notes, "<br>Core Event Notes: ", core_event_notes, "<br>Record ID: ", ifelse(is.na(record_ID), " ", record_ID) , ifelse((level=="MH_alert")|reader_change_alert, "<span style='font-size:16px; font-weight:bold;'><br><br>ALERTS!!!</span>", "<span style='font-size:16px;'><br><br>(no alerts)</span>"), ifelse(dpl_alert, paste0("<br>DPL: ", dpl), ""), ifelse(core_condition_alert, paste0("<br>Core Condition: ", core_condition), ""), ifelse(core_notes_alert, paste0("<br>Core Notes: ", core_notes), ""), ifelse(core_event_notes_alert, paste0("<br>Core Event Notes: ", core_event_notes), ""), ifelse(reader_change_alert, paste0("<br>MH Reader Change: ", reader_transition), ""))
) %>%
droplevels()
shiny::req(!is.null(subdat))
# Calculate total and relative heights
temp_distinct <- subdat %>%
dplyr::select(station_name, marker_horizon_name, core_measurement_number) %>%
dplyr::group_by(station_name, marker_horizon_name) %>%
dplyr::summarize(n_cores = length(unique(core_measurement_number))) # for each MH, how many cores are there?
total_page_ht <- max(100 + 30*sum(temp_distinct$n_cores), 320)
incProgress(1/2, detail = "...creating subplots") # MH for this station
num_subplots <- length(unique(subdat$marker_horizon_name))
subplot_names <- sort(unique(subdat$marker_horizon_name))
MH_list <- lapply(subplot_names, function(j) { # subplot the marker horizons for a station
cat("j = ", j, " // ")
subdat_MH <- dplyr::filter(subdat, marker_horizon_name == j)
# create number matrix to put values in the heatmap cells
template <- subdat_MH %>%
dplyr::select(core_measurement_number, event_date_UTC) %>%
expand(core_measurement_number, event_date_UTC)
if(heat_metric == "raw") {
template %<>%
left_join(subdat_MH[c("marker_horizon_name", "core_measurement_number", "event_date_UTC", "core_measurement_depth_mm", "hover_label", "level", "border_color")], by = c("core_measurement_number", "event_date_UTC")) %>%
dplyr::arrange(event_date_UTC, core_measurement_number)
}
txt <- matrix(pull(template, core_measurement_depth_mm), nrow=length(unique(template$core_measurement_number)))
txt[is.na(txt)] <- " " # convert NA to blank, otherwise it will show as "new text"
# Create discrete color scale
use_cols <- discrete_cols[which(discrete_levels %in% unique(na.omit(template$level)))]
if(length(use_cols) > 0) {
temp_seq <- seq(0,1, length.out = length(use_cols)+1)
rep_seq <- rep(temp_seq[c(-1, -length(temp_seq))], each = 2)
z = c(temp_seq[1], rep_seq, temp_seq[length(temp_seq)])
color_scale <- data.frame(z=z,col=rep(use_cols, each = 2)) # the default color for NA is white
} else {
color_scale <- data.frame(z = c(0, 1), col = rep("#ffd700", 2))
}
plot_ly(
data = template,
text = text,
width = max(800, 52*length(unique(template$event_date_UTC))),
height = total_page_ht, # can't specify heights in subplot, need to set it at this plot_ly level
showscale = FALSE) %>%
plotly::add_heatmap(
x = ~as.factor(event_date_UTC),
y = ~as.integer(core_measurement_number),
text = ~hover_label, # hover information
hoverinfo ="text",
z = ~as.numeric(factor(level, ordered = T, levels = discrete_levels)), # assign discrete colors to the cells
colorscale = color_scale,
xgap = 0.5, # spacing between heatmap cells
ygap = 0.5
) %>%
layout(
hoverlabel = list(align = "left"),
xaxis = list( # x-axis
title = "Survey Date", # not enough space before next subplot. <br> does not work
tickangle = 270,
titlefont=list(size=16, family = "Arial")),
yaxis = list( # y-axis
autorange = "reversed",
dtick = 1)
) %>%
add_annotations( # MH subtitle
text = paste0("Marker Horizon ", unique(template$marker_horizon_name)),
xref = "paper",
yref = "paper",
x = 0,
y = 1 + .03/num_subplots, # was 1.01
xanchor = "left",
yanchor = "bottom", # y anchor uses 'middle', x anchor uses 'center'
showarrow = FALSE,
font=list(size=16, family = "Arial")
) %>%
add_annotations( # these are the cell values
x = ~event_date_UTC,
y = ~as.integer(core_measurement_number),
align = "center",
text = txt, # add the values in the cells
bordercolor = ~border_color,
borderwidth = 2,
showarrow = FALSE)
})
if(num_subplots > 2) {
subplot_marg <- FuncSubplotMargins(num_subplots = num_subplots, tot_page = total_page_ht)
} else {
subplot_marg <- list(hts = rep(1/num_subplots, num_subplots), marg = c(0, 0, 0.15, 0.15))
}
incProgress(1/2, detail = "...putting final plot together")
final_MHheat_plotly <- plotly::subplot(
MH_list,
nrows = length(MH_list),
shareX = TRUE,
shareY = FALSE,
titleX = TRUE,
titleY = FALSE,
heights = subplot_marg$hts,
margin = subplot_marg$marg
) %>%
add_annotations( # Station name as title
x = 0.5,
y = 1 + (30/total_page_ht), #1.1,
text = paste0("Marker horizon data for ", unique(subdat$station_name)),
showarrow = F,
xref="paper",
yref="paper",
xanchor="center",
yanchor="bottom",
font=list(size=20, family = "Arial")
) %>%
add_annotations( # shared y-axis title
x = -0.05,
y = 0.55,
text = "Core Number",
showarrow = F,
xref="paper",
yref="paper",
xanchor="right",
yanchor="middle", # y anchor uses 'middle', x anchor uses 'center'
textangle=-90,
font=list(size=16, family = "Arial")) %>%
layout(
margin = list( # how much of page height is reserved for title, etc.?
t=55,
b=25,
l= 80,
r=40)
)
# final_MHheat_plotly
}) # end progress
return(final_MHheat_plotly)
}
FuncPlotlyMatrixPlot <- function(dat) {
# Function to create plotly heatmaps of raw pin data or diff_pin_height_mm or diff_base_height_mm, organized by station. Using plot_ly because ggplotly is too slow for interactive heat plots b/c it doesn't recognize the input as a heatmap and creates a scatterplot where each rectangle is drawn separately with all the necessary attributes.
#
# Args:
# dat: A filtered SET data frame with raw pin data/change quantile/change threshold classification for a single site
#
# Returns:
# Plotly heat map
#
withProgress(message = "Just a moment", detail = "...formatting data", value = 0, {
double_dat <- dat %>%
ungroup %>%
dplyr::filter(observation_type == "Double Read")
subdat <- dat%>%
ungroup() %>%
dplyr::arrange(station_name, SET_direction, pin_position, event_date_UTC) %>%
dplyr::mutate(
hover_label = paste0("<span style='font-size:16px; font-weight:bold;'>", "Pipe Direction: ", paste0(SET_direction, " (", SET_direction_azimuth, " degrees)"), "</span><br>Pin Position: ", pin_position, "<br>Visit Date: ", event_date_UTC, "<br>LEVEL: ", level_categ, "<br>Height: ", sel_metric, ifelse(!is.na(SET_reader2), paste0("<br>Height2 (DOUBLE READ): ", sel_metric2), ""), "<br>Height Diff: ", sel_diff_metric, "<br>Days Diff: ", switch((rv$sel_DiffFromBase == "diff")+1, diff_days_base, diff_days), "<br>SET Reader: ", SET_reader, ifelse(!is.na(SET_reader2), paste0("<br>SET Reader2 (DOUBLE READ): ", SET_reader2), ""), "<br>Pin Collection: ", pin_collection, "<br>Pin Length: ", pin_length_mm, "<br>Record ID: ", record_ID, ifelse(alert_level, "<span style='font-size:16px; font-weight:bold;'><br><br>ALERTS!!!</span>", "<span style='font-size:16px;'><br><br>(no alerts)</span>"), ifelse(dpl_alert, paste0("<br>DPL: ", dpl), ""), ifelse(pin_flag_alert, paste0("<br>Pin Flag: ", pin_flag_label, "<br>Pin Flag Notes: ", pin_flag_notes), ""), ifelse(veg_notes_alert, paste0("<br>Vegetation Notes: ", vegetation_notes), ""), ifelse(SET_notes_alert, paste0("<br>SET Notes: ", SET_notes), ""), ifelse(analysis_alert & !is.na(exclude_int_reason_ID), paste0("<br>Exclude, Interval Analysis: ", exclude_int_reason_ID, " (", exclude_int_reason, ")"),""),ifelse(analysis_alert & !is.na(exclude_cumul_reason_ID), paste0("<br>Exclude, Cumul Analysis: ", exclude_cumul_reason_ID, " (", exclude_cumul_reason, ")"), ""), ifelse(SET_reader_alert & !is.na(SET_reader_transition), paste0("<br>Set Reader Change: ", SET_reader_transition), ""), ifelse(SET_instrument_alert & !is.na(SET_instrument_transition), paste0("<br>Set Instrument Change: ", SET_instrument_transition), ""), ifelse(pin_collection_alert & !is.na(pin_collection_transition), paste0("<br>Pin Collection Change: ", pin_collection_transition), ""), ifelse(event_notes_alert, paste0("<br>Event Notes: ", event_notes), "")),
combined_change_height = ifelse(!is.na(SET_reader2), paste0("<font size=`4`><b>", sel_diff_metric, " [", sel_metric, "]</b></font>"), paste0( sel_diff_metric, " [", sel_metric, "]"))
) %>%
dplyr::select(record_ID, site_name, station_name, SET_direction_azimuth, SET_direction, pin_position, event_date_UTC, observation_type, pin_position, sel_metric, sel_diff_metric, combined_change_height, diff_days, diff_days_base, level_categ, hover_label, border_color) %>%
droplevels()
subdat$level_categ[is.na(subdat$level_categ)] <-"N/A" # this is necessary so heatmap will still work even if no data
# Calculate total and relative page/plot heights
temp_distinct <- subdat %>%
dplyr::select(station_name, SET_direction, pin_position) %>%
dplyr::group_by(station_name, SET_direction) %>%
dplyr::summarize(n_pins = length(unique(pin_position))) # for each SET direction, how many pins are there?
total_page_ht <- 64 + nrow(temp_distinct) * (30*mean(temp_distinct$n_pins))
incProgress(1/2, detail = "...creating subplots")
# Pipe directions for this station
pipe_dxn_list <- vector("list", length = length(unique(subdat$SET_direction)))
pipe_dxn_list <- lapply(sort(unique(subdat$SET_direction)), function(j) { # subplot the pipe directions for a station
cat("j = ", j, " // ")
subdat_pipe <- dplyr::filter(subdat, SET_direction == j)
# create number matrix to put values in the heatmap cells
template <- subdat_pipe %>%
dplyr::select(pin_position, event_date_UTC) %>%
expand(pin_position, event_date_UTC) %>%
left_join(subdat_pipe[c("SET_direction", "SET_direction_azimuth", "pin_position", "event_date_UTC", "sel_metric", "sel_diff_metric", "combined_change_height", "hover_label", "level_categ", "border_color")], by = c("pin_position", "event_date_UTC")) %>%
dplyr::arrange(event_date_UTC, pin_position)
txt <- matrix(pull(template, combined_change_height),
nrow=length(unique(template$pin_position)))
txt[is.na(txt)] <- "N/A" # convert NA to blank, otherwise it will show as "new text"
# Create discrete color scale
use_cols <- level_colors[which(rv$LevelNames %in% unique(na.omit(template$level_categ)))]
if(length(use_cols) > 0) {
temp_seq <- seq(0,1, length.out = length(use_cols)+1)
rep_seq <- rep(temp_seq[c(-1, -length(temp_seq))], each = 2)
z = c(temp_seq[1], rep_seq, temp_seq[length(temp_seq)])
color_scale <- data.frame(z=z,col=rep(use_cols, each = 2))
} else {
color_scale <- data.frame(z = c(0, 1), col = rep("#ffffff", 2))# the default color for NA is white
}
plot_ly(
data = template,
text = text,
width = max(900, ifelse(rv$sel_SETmetric == "soil_elev_m", 105, 90)*length(unique(template$event_date_UTC))),
height = total_page_ht, # can't specify heights in subplot, need to set it at this plot_ly level
showscale = FALSE) %>%
plotly::add_heatmap(
x = ~as.factor(event_date_UTC),
y = ~as.integer(pin_position),
text = ~hover_label, # hover information
hoverinfo ="text",
z = ~as.numeric(level_categ), # assign discrete colors to the cells
colorscale = color_scale,
xgap = 0.5, # spacing between heatmap cells
ygap = 0.5
) %>%
layout(
hoverlabel = list(align = "left"),
xaxis = list( # x-axis
title = "Survey Date", # not enough space before next subplot. <br> does not work
tickangle = 270,
titlefont=list(size=16, family = "Arial")),
yaxis = list( # y-axis
autorange = "reversed",
dtick = 1),
margin = c(0, 0, 0.2, 0.2)
) %>%
add_annotations( # Pipe Direction subtitle
text = paste0("Pipe Direction ", unique(template$SET_direction), " (", template$SET_direction_azimuth, " degrees)"),
xref = "paper",
yref = "paper",
x = 0,
y = 1.02,
xanchor = "left",
yanchor = "bottom", # y anchor uses 'middle', x anchor uses 'center'
showarrow = FALSE,
font=list(size=16, family = "Arial")
) %>%
add_annotations( # these are the cell values
x = ~event_date_UTC,
y = ~as.integer(pin_position),
align = "center",
text = txt, # add the values in the cells
bordercolor = ~border_color,
borderwidth = 2,
showarrow = FALSE)
})
incProgress(1/2, detail = "...putting final plot together")
title_metric_text <- switch(rv$sel_SETmetric,
pin_height_mm = "RAW pin heights (uncorrected for pin length)",
standardized_soil_elev_mm = "STANDARDIZED pin heights",
soil_elev_m = "ORTHOMETRIC heights")
final_heat_plotly <- plotly::subplot(
pipe_dxn_list,
nrows = length(pipe_dxn_list),
shareX = TRUE,
shareY = FALSE,
titleX = TRUE,
titleY = FALSE
) %>%
add_annotations( # Station name as title
x = 0.5,
y = 1.025,
text = paste0("<br><br>", title_metric_text, " for ", unique(subdat$station_name)),
showarrow = F,
xref="paper",
yref="paper",
xanchor="center",
yanchor="bottom",
font=list(size=20, family = "Arial")
) %>%
add_annotations( # shared y-axis title
x = -0.05,
y = 0.55,
text = "Pin Position",
showarrow = F,
xref="paper",
yref="paper",
xanchor="right",
yanchor="middle", # y anchor uses 'middle', x anchor uses 'center'
textangle=-90,
font=list(size=16, family = "Arial")) %>%
layout(
margin = list(
t=50,
b=20,
l= 80,
r=40)
)
}) # end progress
return(final_heat_plotly)
}
FuncPlotlyPieMatrix <- function(dat, plot_title) {
# Function to create plotly pie chart matrix of pin_height_diff, organized by user-selected grouping.
#
# Args:
# dat: A filtered SET data frame with quantile/threshold classification for a single site
# plot_title: Title for plot page
#
# Returns:
# Page of plotly pie charts
#
stations_vec <- sort(unique(dat$station_name))
date_vec <- sort(unique(dat$event_date_UTC))
# date_vec <- date_vec[-1] # the first survey event won't have any "change in pin height" estimates, so start with second survey event
width_px <- 200 + 150 * length(date_vec) # this is the plot width (paper)
height_px <- 200 + (150 * length(stations_vec)) # this is the plot height (paper)
fig <- plot_ly(
textfont = list(size = 22, color = "white"),
width = width_px,
height = height_px,
)
m <- list(
l = 160,
r = 40,
b = 100,
t = 100,
pad = 0
)
for(s in 1:length(stations_vec)) {
station <- stations_vec[s]
for(d in 2:length(date_vec)) { # the first survey event won't have any "change in pin height" estimates, so start with second survey event
survey_date <- date_vec[d]
fig <- fig %>%
add_pie(data = dplyr::filter(dat, station_name == station & event_date_UTC == survey_date),
name = paste0(station, "_", survey_date),
labels = ~level_categ,
values = ~N,
textposition = 'inside',
textinfo = 'percent',
hoverinfo = 'text',
text = ~hover_label,
marker = list(colors = level_colors, line = list(color = '#FFFFFF', width = 1)),
domain = list(row = s-1, column = d-1))
}
}
date_seq_px <- seq(75, width_px-75, length.out = length(date_vec))/width_px # this is where date labels should align on x-axis, when reference is "paper"
y_seq_px <- seq(50, height_px-50, length.out = length(stations_vec))/height_px
title_loc <- 1 + (90/height_px) #it's into the top margin space, when reference is "container"
legend_loc <- 1 + (50/height_px)
dates_loc_bottom <- -1 * (50/height_px)
dates_labels_bottom <- list(
text = as.list(as.character(date_vec)),
xref = "paper",
yref = "container",
yanchor = "center",
xanchor = "center",
font =list(size = ifelse(length(date_vec)<3, 12, 14)),
align = "right",
x = date_seq_px,
y = dates_loc_bottom,
showarrow = FALSE)
station_labels_left <- list(
text = as.list(sort(unique(dat$station_name), decreasing = TRUE)),
xref = "paper",
yref = "paper",
xanchor = "right",
yanchor = "center",
font =list(size = 14),
align = "center",
x = 0,
y = y_seq_px,
showarrow = FALSE)
fig_final <- fig %>% layout(
margin = m,
title = list(
text = plot_title,
x = 0.5,
y = title_loc,
xref = "container", # gets cut off if referenced to the plot only ("paper")
yref = "paper",
xanchor = "center",
yanchor = "center"),
showlegend = TRUE,
legend = list(
orientation = "h",
x = 0.5,
xref = "container",
yref = "paper",
xanchor = "center",
y = legend_loc,
yanchor = "center"),
grid=list(
rows=length(stations_vec),
columns=length(date_vec)),
autosize = FALSE,
annotations = station_labels_left)
fig_final <- fig_final %>% layout(annotations = dates_labels_bottom)
fig_final <- fig_final %>% layout(
title = "(Row = Station; Column = Survey Date)",
showlegend = FALSE,
grid=list(
rows=length(unique(dat$station_name)),
columns=length(date_vec)),
xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
autosize = FALSE,
width = 150 * length(date_vec), # this is the plot width (paper)
height = 150 * length(unique(dat$station_name)) # this is the plot height (paper)
)
return(fig_final)
}
FuncOrderCheck <- function(import = TRUE, examine = TRUE) {
# Function to check if data have been imported and filtered
if(import == TRUE) {
shiny::validate(
need(!is.null(rv$DataSET), message = "No data available. Please first import SET data (green buttons on 'Home' tab)."))
}
if(examine == TRUE) {
shiny::req(!is.null(rv$DataSET))
shiny::validate(
need(!is.null(rv$SubDataSET), message = "Please first use the 'Sampling Summary' tab to choose a park and a subset of data to examine."))
shiny::validate(
need(!is.null(rv$SubDataSummary), message = "Please first use the 'Sampling Summary' tab to choose a park and a subset of data to examine."))
}
}
FuncFormatSET_NERRs <- function(dat) {
temp_NERRs <- dat %>%
dplyr::filter(park_code %in% input$sel_export_parks) %>%
dplyr::mutate(
reserve = park_code,
set_id = paste0(station_name, "_Pipe", SET_direction_azimuth),
year = lubridate::year(event_date_UTC),
month = lubridate::month(event_date_UTC),
day = lubridate::day(event_date_UTC),
arm_position = SET_direction_azimuth,
arm_qaqc_code = NA,
pin_number = paste0("pin_", pin_position),
height_mm = pin_height_mm,
qaqc_code = NA) %>%
dplyr::select(reserve, set_id, year, month, day, arm_position, arm_qaqc_code, pin_number, height_mm, qaqc_code)
return(temp_NERRs)
}
FuncAllNoneButtons <- function(cond, name_all, name_none) {
# Function to create 'Select All' and 'Select None' action buttons
#
# Args:
# cond: The input ID that needs to be defined for buttons to show (enter as input.XXX rather than as input$XXX)
# name_all: ID to assign to 'Select All' button
# name_none: ID to assign to 'Select None' button
#
conditionalPanel(
condition = paste0("typeof ", cond, " !== 'undefined'"),
actionButton(name_all, "Select All", style="color:black; display:inline-block; border:1px; padding:4px 12px;"),
actionButton(name_none, "Select None", style="color:black; display:inline-block; border:1px; padding:4px 12px;")
)
}
```
```{r action_buttons}