generated from movestore/Template_R_Shiny_App
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShinyModule.R
More file actions
1068 lines (830 loc) · 40.5 KB
/
ShinyModule.R
File metadata and controls
1068 lines (830 loc) · 40.5 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
####################
# setup
####################
# load packages
library("shiny")
library("move2")
library("sf")
library("leaflet")
library("leaflet.extras")
library("pals")
library("mapview")
library("geosphere")
library("plotly")
library("DT")
library("RColorBrewer")
library("dplyr")
library("shinybusy")
library("leafem")
# disable scientific notation
options(scipen = 999)
# create list with choices for date range dropdown and set default choice
choices_date_range <- list("last day" = 1,
"last week" = 7,
"last 30 days" = 30,
"last 60 days" = 60,
"last 90 days" = 90,
"last 180 days" = 180,
"last year" = 365,
"all time" = 99999)
default_date_range <- 180
# set limits and default for max distance
limit_lower_max_distance <- 1
limit_upper_max_distance <- 100000
default_max_distance <- 100
# set limits and default for min duration
limit_lower_min_duration <- 1
limit_upper_min_duration <- 240
default_min_duration <- 24
# set max number of last hours for calculating distance to last location
max_min_duration_parameter <- 240
# set limit for observations before automatic data reduction is triggered
limit_upper_observations <- 100000
# set max number of last n days to keep all locations for during automatic data reduction
limit_upper_last_n_days_for_data_reduction <- 10
# set max number of tracks to be shown on map when all individuals are selected
fixed_track_limit <- 10
# set limits and default for inactivity threshold
default_inactivity_threshold <- 30
limit_lower_inactivity_threshold <- 1
limit_upper_inactivity_threshold <- 99999
####################
# user interface
####################
shinyModuleUserInterface <- function(id, label) {
# all IDs of UI functions need to be wrapped in ns()
ns <- NS(id)
# create function to insert linebreaks
linebreaks <- function(n){HTML(strrep(br(), n))}
tagList(
titlePanel("Stationarity Dashboard"),
tags$style(type = "text/css", ".col-sm-9 {padding: 15px;}"), # prevent graphs from overlapping
fluidRow(
column(2,
actionButton(ns("about_button"),
"Show app info")
),
column(2,
downloadButton(ns("download_table"),
"Download table")
)
),
linebreaks(1),
fluidRow(
column(2,
selectInput(ns("dropdown_individual"),
"Individual:",
choices = c("all"))
),
column(2,
selectInput(ns("dropdown_date_range"),
"Date range:",
choices = choices_date_range,
selected = c("last 180 days" = default_date_range))
),
column(2,
numericInput(ns("max_distance"),
"Max. distance (m):",
default_max_distance,
min = limit_lower_max_distance,
max = limit_upper_max_distance)
),
column(2,
numericInput(ns("min_duration"),
"Min. duration (h):",
default_min_duration,
min = limit_lower_min_duration,
max = limit_upper_min_duration)
),
column(1,
checkboxInput(ns("checkbox_inactivity_threshold"),
"Inactivity threshold",
TRUE)
),
column(2,
numericInput(ns("inactivity_threshold"),
"Inactivity threshold (d):",
default_inactivity_threshold,
min = limit_lower_inactivity_threshold,
max = limit_upper_inactivity_threshold)
)
),
fluidRow(
column(12,
dataTableOutput(ns("movement_summary"))
)
),
fluidRow(
column(7,
checkboxInput(ns("checkbox_full_map"),
"Limit map to 10 tracks",
TRUE),
leafletOutput(ns("map"))
),
column(5,
linebreaks(2),
plotlyOutput(ns("time_series"))
)
)
)
}
####################
# server
####################
# The parameter "data" is reserved for the data object passed on from the previous app
shinyModule <- function(input, output, session, data) {
# all IDs of UI functions need to be wrapped in ns()
ns <- session$ns
# make input data reactive so that it can be returned later if unmodified
current <- reactiveVal(data)
# show app info when about button is clicked
observeEvent(input$about_button, {
showModal(modalDialog(
title = "About this app",
HTML(
"This app helps identify stationary animals in movement data.<br><br>
It consists of three components:
<li>statistical movement summary table</li>
<li>map with animal tracks</li>
<li>time series plot of daily distances moved</li><br>
<b>Filters and inputs:</b>
<li>The date range filter applies to all individuals in a given dataset and all three components of the app.</li>
<li>Selecting an individual will not affect the table.
Only the map and time series plot will be filtered according to the selected individual.</li>
<li>The max. distance input sets the distance to the last coordinates which an individual has to have moved
within a given amount of time to not be considered stationary.</li>
<li>This given amount of time is set through the min. duration input.</li>
<li>If the inactivity threshold check box is checked,
all individuals without a data point between today and today minus the set number of days are automatically marked as stationary.</li>
<li>If the inactivity threshold check box is not checked, the inactivity threshold numeric input is ignored.</li><br>
<b>Potential workflow:</b><br>
A potential workflow, after setting the max. distance and min. duration inputs,
could start by spotting a single animal of interest in either the table or the map.
Then the data can be filtered for this specific animal and different date ranges can also be analyzed.
A date range always refers to the last n days of each animal's tracking data time series.<br><br>
<b>Notes:</b>
<li>Please refer to the documentation on GitHub for more details.</li>
<li>Aggregation happens at a daily resolution.</li>
<li>Distances are calculated in meters (using Vincenty ellipsoid great circle distance).</li>
<li>Please note that the app performs best with rather small datasets, containing not too many individuals.
This is mainly because calculating distances between coordinates is computation-intensive
when there are frequent location measurements (e. g. a fix every minute).</li>
<li>An automatic data reduction is triggered when the loaded dataset exceeds a certain limit.</li>
<li>Plotting many locations for many individuals on the map also slows the app down.</li>
<li>Rendering the map and time series plot for the first time after starting the app may take some time.</li>
<li>If the check box to limit the number of tracks on the map is checked,
tracks are shown only for the first 10 individuals
(selected from the dataset's respective id column in ascending order).</li>"
)
))
})
# generate values for dropdown individual
observe({
# show modal during data loading
showModal(modalDialog("Loading data...", footer = NULL))
# wait until the data is loaded
if (is.null(data)) return()
unique_individuals <- sort(as.character(unique(mt_track_id(data))))
keys <- c(unique_individuals, "all")
values <- c(unique_individuals, "all")
key_value_list <- setNames(values, keys)
updateSelectInput(session, "dropdown_individual", choices = key_value_list, selected = c("all" = "all"))
# remove modal after data loading
removeModal()
})
# ensure that max distance is within limits
observe({
if (input$max_distance > limit_upper_max_distance || input$max_distance < limit_lower_max_distance) {
showModal(
modalDialog(
title = strong("Warning!", style = "font-size:24px; color: red;"),
p(paste0("Input value for max. distance exceeds limits (min: ",
limit_lower_max_distance,
"; max: ",
limit_upper_max_distance,
"). Reset to default."),
style = "font-size:16px"),
footer = modalButton("Close"))
)
updateNumericInput(session, "max_distance", value = default_max_distance)
}
})
# ensure that min duration is within limits
observe({
if (input$min_duration > limit_upper_min_duration || input$min_duration < limit_lower_min_duration) {
showModal(
modalDialog(
title = strong("Warning!", style = "font-size:24px; color: red;"),
p(paste0("Input value for min. duration exceeds limits (min: ",
limit_lower_min_duration,
"; max: ",
limit_upper_min_duration,
"). Reset to default."),
style = "font-size:16px"),
footer = modalButton("Close"))
)
updateNumericInput(session, "min_duration", value = default_min_duration)
}
})
# ensure that inactivity threshold is within limits
observe({
if (input$inactivity_threshold > limit_upper_inactivity_threshold || input$inactivity_threshold < limit_lower_inactivity_threshold) {
showModal(
modalDialog(
title = strong("Warning!", style = "font-size:24px; color: red;"),
p(paste0("Input value for inactivity threshold exceeds limits (min: ",
limit_lower_inactivity_threshold,
"; max: ",
limit_upper_inactivity_threshold,
"). Reset to default."),
style = "font-size:16px"),
footer = modalButton("Close"))
)
updateNumericInput(session, "inactivity_threshold", value = default_inactivity_threshold)
}
})
##### process loaded data
rctv_data_processed <- reactive({
# show modal during data processing
show_modal_spinner(text = "Processing the input data and calculating distances between locations. This may take a moment.
Rendering the map and time series for the first time may also take a couple minutes.
Please wait.")
# ensure that data is in epsg 4326
data_transformed <- st_transform(data, 4326)
# extract relevant data from move object and create dataframe
individuals <- mt_track_id(data_transformed)
timestamps <- mt_time(data_transformed)
long <- st_coordinates(data_transformed)[, 1]
lat <- st_coordinates(data_transformed)[, 2]
data_df <- data.frame(individuals, timestamps, long, lat)
# reset row names
row.names(data_df) <- NULL
# cast individuals to character
data_df$individuals <- as.character(data_df$individuals)
# get individuals
individuals <- sort(unique(data_df$individuals))
# create year and date columns
data_df$date <- as.Date(format(data_df$timestamps, format = "%Y-%m-%d"))
data_df$year <- as.integer(format(data_df$timestamps, format = "%Y"))
# create empty dataframe to store processed individual data
data_processed <- data.frame(matrix(ncol = 5, nrow = 0))
processed_data_columns <- c("individuals",
"timestamps",
"long",
"lat",
"date")
colnames(data_processed) <- processed_data_columns
# process last n days of observations per individual
for (individual in individuals) {
# filter data based on individual
individual_data <- data_df[data_df$individuals == individual, ]
# subset data to relevant columns
individual_data <- individual_data[ , processed_data_columns]
# drop rows with missing values
individual_data <- na.omit(individual_data)
# drop duplicated rows
individual_data <- individual_data[!duplicated(individual_data[c("individuals", "timestamps")]), ]
# extract min and max date
min_date <- min(individual_data$date)
max_date <- max(individual_data$date)
# filter data based on date range
individual_data <- individual_data[(individual_data$date > min_date) & (individual_data$date <= max_date), ]
# append processed data to existing dataframe
data_processed <- rbind(data_processed, individual_data)
}
# order data
data_processed <- data_processed[order(data_processed$individuals, data_processed$timestamps), ]
# create lag columns
data_processed$individuals_lag <- c(NA, head(data_processed$individuals, -1))
data_processed$long_lag <- c(NA, head(data_processed$long, -1))
data_processed$lat_lag <- c(NA, head(data_processed$lat, -1))
data_processed$individuals_lag <- ifelse(data_processed$individuals == data_processed$individuals_lag,
data_processed$individuals_lag,
NA)
data_processed$long_lag <- ifelse(data_processed$individuals == data_processed$individuals_lag,
data_processed$long_lag,
NA)
data_processed$lat_lag <- ifelse(data_processed$individuals == data_processed$individuals_lag,
data_processed$lat_lag,
NA)
# create function to calculate distance between coordinates
calculate_distance_in_meters_between_coordinates <- function(long_a, lat_a, long_b, lat_b) {
if(anyNA(c(long_a, lat_a, long_b, lat_b))) return(NA)
distm(c(long_a, lat_a), c(long_b, lat_b), fun = distVincentyEllipsoid)
}
# calculate distance between two successive coordinates
data_processed$distance_meters_successive <- mapply(long_a = data_processed$long,
lat_a = data_processed$lat,
long_b = data_processed$long_lag,
lat_b = data_processed$lat_lag,
FUN = calculate_distance_in_meters_between_coordinates)
# drop rows with missing distances
data_processed <- data_processed %>%
filter(!is.na(distance_meters_successive))
# get max date per individual
max_dates <- data_processed %>%
group_by(individuals) %>%
summarise(max_date = max(date))
# get last timestamp and coordinates per individual
last_timestamps_coordinates <- data_processed %>%
group_by(individuals) %>%
arrange(timestamps) %>%
filter(row_number() == n()) %>%
rename(timestamps_last = timestamps,
long_last = long,
lat_last = lat) %>%
select(individuals,
timestamps_last,
long_last,
lat_last)
# join data processed and last timestamps and coordinates
data_processed <- data_processed %>%
left_join(last_timestamps_coordinates, by = "individuals")
# calculate difference between given and last timestamp
data_processed$difference_hours_last <- as.numeric(difftime(data_processed$timestamps_last, data_processed$timestamps, units ="hours"))
# calculate distance between given and last coordinates
# only for time period within maximum of minimum duration parameter to avoid calculating unnecessary distances
data_processed_max_time_period <- data_processed %>%
filter(difference_hours_last <= max_min_duration_parameter)
data_processed_max_time_period$distance_meters_last <- mapply(long_a = data_processed_max_time_period$long,
lat_a = data_processed_max_time_period$lat,
long_b = data_processed_max_time_period$long_last,
lat_b = data_processed_max_time_period$lat_last,
FUN = calculate_distance_in_meters_between_coordinates)
data_processed <- data_processed %>%
filter(difference_hours_last > max_min_duration_parameter) %>%
mutate(distance_meters_last = NA) %>%
rbind(data_processed_max_time_period)
# drop columns that are not needed anymore
columns_to_drop <- c("individuals_lag",
"long_lag",
"lat_lag",
"timestamps_last",
"long_last",
"lat_last")
data_processed <- subset(data_processed, select = !(names(data_processed) %in% columns_to_drop))
# create reduced version of data to be plotted if all individuals are selected if amount of data exceeds limit
if (nrow(data_processed) > limit_upper_observations) {
# get first location per individual
locations_first <- data_processed %>%
group_by(individuals) %>%
arrange(individuals, timestamps) %>%
filter(row_number() == 1) %>%
select(individuals,
timestamps,
long,
lat)
# get one location per day and individual for last year without last n days
locations_last_year_without_last_n_days <- data_processed %>%
left_join(max_dates, by = "individuals") %>%
filter(date < max_date - limit_upper_last_n_days_for_data_reduction) %>%
group_by(individuals, date) %>%
summarise(long = mean(long),
lat = mean(lat),
.groups = "keep") %>%
rename(timestamps = date) %>%
group_by(individuals) %>%
slice(-1)
# get all locations per individual for last n days because this period is the most interesting regarding stationarity
locations_last_n_days <- data_processed %>%
left_join(max_dates, by = "individuals") %>%
filter(date >= max_date - limit_upper_last_n_days_for_data_reduction) %>%
select(individuals,
timestamps,
long,
lat)
data_processed_reduced <- locations_first %>%
rbind(locations_last_year_without_last_n_days) %>%
rbind(locations_last_n_days) %>%
mutate(date = as.Date(format(timestamps, format = "%Y-%m-%d"))) %>%
arrange(individuals, timestamps)
} else {
data_processed_reduced_columns <- c("individuals",
"timestamps",
"long",
"lat",
"date")
data_processed_reduced <- data.frame(matrix(ncol = length(data_processed_reduced_columns), nrow = 0))
colnames(data_processed_reduced) <- data_processed_reduced_columns
}
# remove objects that are not needed anymore
rm(data_df,
individual_data,
last_timestamps_coordinates,
data_processed_max_time_period)
# remove modal after data processing and notify user
remove_modal_spinner()
notify_success("Processing the data and calculating distances complete. Please wait for the map and time series to be rendered.")
# show warning when loaded data exceeds certain amount of observations
if (nrow(data_processed) > limit_upper_observations) {
showModal(
modalDialog(
title = strong("Warning!", style = "font-size:24px; color: red;"),
p(paste0("The data you loaded exceeds ", limit_upper_observations, " observations.
To keep the app performant,
the amount of data displayed on the map when all individuals are selected is reduced as follows:
Keep the first location per individual and all locations within the last ", limit_upper_last_n_days_for_data_reduction, " days per individual;
Calculate the mean location per day for the last year up to the last ", limit_upper_last_n_days_for_data_reduction, " days for each individual.
Should a single individual exceed ", limit_upper_observations, " observations,
the same procedure is applied when the respective individual is selected.
The statistics table and time series plot are not affected by the automatic data reduction.
Please consider loading less data to avoid triggering the automatic data reduction."),
style = "font-size:16px"),
footer = modalButton("Close"))
)
}
list(data_processed = data_processed,
data_processed_reduced = data_processed_reduced,
max_dates = max_dates)
})
##### check individuals for stationarity
rctv_stationary_individuals <- reactive({
# load reactive data
data_processed <- rctv_data_processed()$data_processed
# get max distance
max_distance <- as.numeric(input$max_distance)
# get min duration
min_duration <- as.numeric(input$min_duration)
if (input$checkbox_inactivity_threshold) {
# get inactivity threshold
inactivity_threshold <- as.numeric(input$inactivity_threshold)
# get non-stationary individuals if there are any
non_stationary_individuals <- data_processed %>%
filter((difference_hours_last <= min_duration)
& (distance_meters_last > max_distance)) %>%
filter(date >= Sys.Date() - inactivity_threshold) %>%
distinct(individuals)
} else {
# get non-stationary individuals if there are any
non_stationary_individuals <- data_processed %>%
filter((difference_hours_last <= min_duration)
& (distance_meters_last > max_distance)) %>%
distinct(individuals)
}
# get stationary individuals if there are any
stationary_individuals <- data_processed %>%
distinct(individuals) %>%
anti_join(non_stationary_individuals, by = "individuals") %>%
mutate(stationary = "yes")
stationary_individuals
})
##### filter processed data
rctv_data_processed_filtered <- reactive({
# load reactive data
data_processed <- rctv_data_processed()$data_processed
data_processed_reduced <- rctv_data_processed()$data_processed_reduced
max_dates <- rctv_data_processed()$max_dates
# get last n days
last_n_days <- as.numeric(input$dropdown_date_range)
# filter data according to selected date range
data_processed_filtered <- data_processed %>%
left_join(max_dates, by = "individuals") %>%
filter(date >= max_date - last_n_days)
if (nrow(data_processed_reduced) > 0) {
data_processed_reduced_filtered <- data_processed_reduced %>%
left_join(max_dates, by = "individuals") %>%
filter(date >= max_date - last_n_days)
} else {
data_processed_reduced_filtered <- data_processed_reduced
}
# get individuals
individuals <- sort(unique(data_processed_filtered$individuals))
list(data_processed_filtered = data_processed_filtered,
data_processed_reduced_filtered = data_processed_reduced_filtered,
individuals = individuals)
})
##### aggregate filtered processed data
rctv_data_aggregated <- reactive({
# load reactive data
data_processed_filtered <- rctv_data_processed_filtered()$data_processed_filtered
# aggregate distances by date and individual
data_aggregated <- data_processed_filtered %>%
group_by(date, individuals) %>%
summarise(daily_distance_meters = sum(distance_meters_successive, na.rm = TRUE),
measures_per_date = n(),
.groups = "keep")
# get individuals
individuals <- sort(unique(data_aggregated$individuals))
list(data_aggregated = data_aggregated,
individuals = individuals)
})
##### time series
rctv_time_series <- reactive({
# load reactive data
data_aggregated <- rctv_data_aggregated()$data_aggregated
individuals <- rctv_data_aggregated()$individuals
# select individual to plot data for
if (input$dropdown_individual == "all") {
individual <- individuals[1]
} else {
individual <- input$dropdown_individual
}
# get data to plot
data_to_plot <- data_aggregated[data_aggregated$individuals == individual, ]
start_date <- min(data_to_plot$date)
end_date <- max(data_to_plot$date)
# generate sequence of dates and fill missing dates with zero
date_seq <- data.frame(date = seq(start_date, end_date, by = "day"))
data_to_plot <- date_seq %>%
left_join(data_to_plot)
data_to_plot[is.na(data_to_plot)] <- 0
# set date scale
if (dim(data_to_plot)[1] > 30) {
scale <- "1 week"
} else {
scale <- "1 day"
}
# plot time series for selected individual
p <- plot_ly(as.data.frame(data_to_plot),
x = ~date,
y = ~daily_distance_meters / 1000,
type = "scatter",
mode = "lines",
name = individual) %>%
layout(showlegend = TRUE,
legend = list(orientation = "h",
xanchor = "center",
x = 0.5,
y = 1),
title = "Do the last distances moved look anomalous to you?",
yaxis = list(title = "Daily distance (km)"),
xaxis = list(title = "Date"))
p
})
output$time_series <- renderPlotly({ rctv_time_series() })
##### map
rctv_map <- reactive({
# load reactive data
data_processed_filtered <- rctv_data_processed_filtered()$data_processed_filtered
data_processed_reduced_filtered <- rctv_data_processed_filtered()$data_processed_reduced_filtered
individuals <- rctv_data_processed_filtered()$individuals
stationary_individuals <- rctv_stationary_individuals()
# set map colors and parameters
qual_col_pals <- brewer.pal.info[brewer.pal.info$category == "qual", ]
col_vector <- tail(unlist(mapply(brewer.pal, qual_col_pals$maxcolors, rownames(qual_col_pals))), -4)
line_opacity <- 0.8
line_weight <- 2
circle_opacity <- 0.5
circle_fill_opacity <- 0.3
legend_opacity <- 0.6
# store individual colors
individual_colors <- col_vector[1:length(individuals)]
# filter for individual
if (input$dropdown_individual == "all") {
# do nothing and proceed
} else {
data_processed_filtered <- data_processed_filtered[data_processed_filtered$individuals == input$dropdown_individual, ]
data_processed_reduced_filtered <- data_processed_reduced_filtered[data_processed_reduced_filtered$individuals == input$dropdown_individual, ]
}
# get remaining individual(s)
remaining_individuals <- unique(data_processed_filtered$individuals)
length_remaining_individuals <- length(remaining_individuals)
# limit number of shown tracks on map if needed
track_limit <- length_remaining_individuals
if (input$checkbox_full_map) {
track_limit <- fixed_track_limit
}
# create map with scale, tiles and controls
map <- leaflet() %>%
addTiles() %>%
addScaleBar(position = "topleft") %>%
addProviderTiles("Esri.WorldTopoMap", group = "TopoMap") %>%
addProviderTiles("Esri.WorldImagery", group = "Aerial") %>%
addLayersControl(position = "topleft", baseGroups = c("StreetMap", "Aerial"),
overlayGroups = c("Lines", "Points"),
options = layersControlOptions(collapsed = FALSE)) %>%
leafem::addMouseCoordinates()
# populate map
if (length(remaining_individuals) > 1) {
for (i in seq(along = head(remaining_individuals, n = track_limit))) {
if (nrow(data_processed_reduced_filtered) == 0) {
# filter data for individual
data_processed_filtered_individual <- data_processed_filtered[data_processed_filtered$individuals == remaining_individuals[i], ]
# add lines and points
map <- map %>%
addPolylines(data = data_processed_filtered_individual,
lng = ~long,
lat = ~lat,
color = individual_colors[i],
opacity = line_opacity,
weight = line_weight,
group = "Lines") %>%
addCircles(data = data_processed_filtered_individual,
lng = ~long,
lat = ~lat,
color = individual_colors[i],
opacity = circle_opacity,
fillOpacity = circle_fill_opacity,
label = ~timestamps,
group = "Points")
} else {
# filter data for individual
data_processed_filtered_individual <- data_processed_reduced_filtered[data_processed_reduced_filtered$individuals == remaining_individuals[i], ]
# add lines and points
map <- map %>%
addPolylines(data = data_processed_filtered_individual,
lng = ~long,
lat = ~lat,
color = individual_colors[i],
opacity = line_opacity,
weight = line_weight,
group = "Lines") %>%
addCircles(data = data_processed_filtered_individual,
lng = ~long,
lat = ~lat,
color = individual_colors[i],
opacity = circle_opacity,
fillOpacity = circle_fill_opacity,
label = ~timestamps,
group = "Points")
}
}
# add marker for last location of stationary individuals if there are any
if (nrow(stationary_individuals) > 0) {
for (remaining_individual in remaining_individuals) {
stationary_individual <- unique(stationary_individuals[stationary_individuals$individuals == remaining_individual, ]$individuals)
if (length(stationary_individual) > 0) {
data_processed_filtered_stationary <- tail(data_processed_filtered[data_processed_filtered$individuals == stationary_individual, ], 1)
stationary_long <- data_processed_filtered_stationary$long
stationary_lat <- data_processed_filtered_stationary$lat
stationary_time <- data_processed_filtered_stationary$timestamps
stationary_icon <- awesomeIcons(icon = "map-pin",
library = "fa",
markerColor = "black")
map <- map %>%
addAwesomeMarkers(lng = stationary_long,
lat = stationary_lat,
icon = stationary_icon,
label = paste0("Stationary at: ", stationary_time))
}
}
}
# don't show legend if map is showing more than 10 tracks
if (track_limit <= fixed_track_limit) {
map <- map %>%
addLegend(position = "topright",
colors = individual_colors,
opacity = legend_opacity,
labels = remaining_individuals)
}
} else {
# get index of selected individual
selected_index <- which(individuals == remaining_individuals)
# get first and last long, lat and time
first_long <- head(data_processed_filtered, 1)$long
first_lat <- head(data_processed_filtered, 1)$lat
first_time <- head(data_processed_filtered, 1)$timestamps
last_long <- tail(data_processed_filtered, 1)$long
last_lat <- tail(data_processed_filtered, 1)$lat
last_time <- tail(data_processed_filtered, 1)$timestamps
# create start and end icons
start_icon <- awesomeIcons(icon = "map-pin",
library = "fa",
markerColor = "white")
end_icon <- awesomeIcons(icon = "map-pin",
library = "fa",
markerColor = "red")
if (nrow(data_processed_filtered) <= limit_upper_observations) {
# add lines and points
map <- map %>%
addPolylines(data = data_processed_filtered,
lng = ~long,
lat = ~lat,
color = individual_colors[selected_index],
opacity = line_opacity,
weight = line_weight,
group = "Lines") %>%
addCircleMarkers(data = data_processed_filtered,
lng = ~long,
lat = ~lat,
color = individual_colors[selected_index],
opacity = circle_opacity,
fillOpacity = circle_fill_opacity,
label = ~timestamps,
clusterOptions = markerClusterOptions(),
group = "Points")
} else {
# add lines and points
map <- map %>%
addPolylines(data = data_processed_reduced_filtered,
lng = ~long,
lat = ~lat,
color = individual_colors[selected_index],
opacity = line_opacity,
weight = line_weight,
group = "Lines") %>%
addCircleMarkers(data = data_processed_reduced_filtered,
lng = ~long,
lat = ~lat,
color = individual_colors[selected_index],
opacity = circle_opacity,
fillOpacity = circle_fill_opacity,
label = ~timestamps,
clusterOptions = markerClusterOptions(),
group = "Points")
}
# add markers
map <- map %>%
addAwesomeMarkers(lng = first_long,
lat = first_lat,
icon = start_icon,
label = paste0("First location at: ", first_time)) %>%
addAwesomeMarkers(lng = last_long,
lat = last_lat,
icon = end_icon,
label = paste0("Last location at: ", last_time))
# add legend
map <- map %>%
addLegend(position = "topright",
colors = individual_colors[selected_index],
opacity = legend_opacity,
labels = remaining_individuals)
}
map
})
output$map <- renderLeaflet({ rctv_map() })
##### movement summary
rctv_movement_summary <- reactive({
# load reactive data
data_processed_filtered <- rctv_data_processed_filtered()$data_processed_filtered
data_aggregated <- rctv_data_aggregated()$data_aggregated
individuals <- rctv_data_aggregated()$individuals
stationary_individuals <- rctv_stationary_individuals()
# create empty dataframe to store movement summary
movement_summary_columns <- c("individual",
"first timestamp",
"first location",
"last timestamp",
"last location",
"#days w measures",
"#days w/o measures",
"total distance (km)",
"median distance (km)")
movement_summary <- data.frame(matrix(ncol = length(movement_summary_columns), nrow = 0))
colnames(movement_summary) <- movement_summary_columns
# compute movement summary for last n days per individual
for (individual in individuals) {
# filter data based on individual
individual_data_processed_filtered <- data_processed_filtered[data_processed_filtered$individuals == individual, ]
individual_data_aggregated <- data_aggregated[data_aggregated$individuals == individual, ]
# get first and last timestamp
first_timestamp <- min(individual_data_processed_filtered$timestamps)
last_timestamp <- max(individual_data_processed_filtered$timestamps)
# get first and last location
first_long <- head(individual_data_processed_filtered, 1)$long
last_long <- tail(individual_data_processed_filtered, 1)$long
first_lat <- head(individual_data_processed_filtered, 1)$lat
last_lat <- tail(individual_data_processed_filtered, 1)$lat
# get number of days with and without measures
days_with_measures <- dim(individual_data_aggregated)[1]
days_without_measures <- as.numeric(input$dropdown_date_range) - days_with_measures
days_without_measures <- ifelse(days_without_measures < 0, 0, days_without_measures)
# get total and median distance
total_distance <- sum(individual_data_aggregated$daily_distance_meters)
median_distance <- median(individual_data_aggregated$daily_distance_meters)