forked from marquetlab/GCM_compareR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
executable file
·2155 lines (1886 loc) · 113 KB
/
server.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
if (!require("pacman")) install.packages("pacman")
pacman::p_load(shiny, shinythemes, shinyjs, shinycssloaders, plotly, leaflet, leaflet.extras, shiny, tidyverse, kableExtra, raster, plotly, leaflet, leaflet.extras, sp, sf, rgdal, fasterize, maps, maptools, rgeos)
# library(shiny)
# library(tidyverse)
# library(kableExtra)
# library(raster)
# library(plotly)
# library(leaflet)
# library(leaflet.extras)
# # Maps
# library(sp)
# library(sf)
# library(rgdal)
# library(fasterize)
# library(maps)
# library(maptools)
# Spatial data
world <- maps::map("world", fill = TRUE, plot = FALSE)
world_map <- map2SpatialPolygons(world, sub(":.*$", "", world$names))
world_map <- SpatialPolygonsDataFrame(world_map,
data.frame(country = names(world_map),
stringsAsFactors = FALSE),
FALSE)
world_sf <- st_as_sf(world_map)
biomes <- read_sf("data/biomes.shp")
biomes_sp <- readOGR("data", "biomes")
ecorregions <- read_sf("data/Ecoregions2017.shp")
ecorregions_sp <- readOGR("data", "Ecoregions2017")
# Table of available GCMs
table_GCMs <- read_csv("data/GCMs_details.csv") %>%
dplyr::select(-"Actual name")
##############################################################################################################################################################################
######################################## SERVER ######################################################################################################################
##############################################################################################################################################################################
# Initialize object to store reactive values
rvs <- reactiveValues(ext_user = extent(-180, 180, -60, 90),
still_no_analyse = NULL,
available_gcms = NULL)
server <- function(input, output) {
# ##################################################
# #### Prepare input values and hide options
# ##################################################
# ### Asure that hidden input provide a valid initial value
output$sel_gcms <- eventReactive(input$sel_gcms, TRUE, ignoreInit = TRUE)
output$bio_vars <- eventReactive(input$bio_vars, TRUE, ignoreInit = TRUE)
output$selection_gcms <- eventReactive(input$selection_gcms, TRUE, ignoreInit = TRUE)
output$res_sel <- eventReactive(input$res_sel, TRUE, ignoreInit = TRUE)
output$year_type <- eventReactive(input$year_type, TRUE, ignoreInit = TRUE)
output$rcp_type <- eventReactive(input$rcp_type, TRUE, ignoreInit = TRUE)
output$compare_type <- eventReactive(input$compare_type, TRUE, ignoreInit = TRUE)
output$compare_type_bio_bio <- eventReactive(input$compare_type_bio_bio, TRUE, ignoreInit = TRUE)
output$compare_type_bio_several <- eventReactive(input$compare_type_bio_several, TRUE, ignoreInit = TRUE)
output$gcm_to_plot <- eventReactive(input$gcm_to_plot, TRUE, ignoreInit = TRUE)
output$bio_to_plot <- eventReactive(input$bio_to_plot, TRUE, ignoreInit = TRUE)
output$map_pre_delta_gcm <- eventReactive(input$map_pre_delta_gcm, TRUE, ignoreInit = TRUE)
output$map_pre_delta_bio <- eventReactive(input$map_pre_delta_bio, TRUE, ignoreInit = TRUE)
outputOptions(output, "sel_gcms", suspendWhenHidden = FALSE) # The key is suspendWhenHidden = FALSE
outputOptions(output, "bio_vars", suspendWhenHidden = FALSE)
outputOptions(output, "selection_gcms", suspendWhenHidden = FALSE)
outputOptions(output, "res_sel", suspendWhenHidden = FALSE)
outputOptions(output, "year_type", suspendWhenHidden = FALSE)
outputOptions(output, "rcp_type", suspendWhenHidden = FALSE)
outputOptions(output, "compare_type", suspendWhenHidden = FALSE)
outputOptions(output, "compare_type_bio_bio", suspendWhenHidden = FALSE)
outputOptions(output, "compare_type_bio_several", suspendWhenHidden = FALSE)
outputOptions(output, "bio_to_plot", suspendWhenHidden = FALSE)
outputOptions(output, "gcm_to_plot", suspendWhenHidden = FALSE)
outputOptions(output, "map_pre_delta_gcm", suspendWhenHidden = FALSE)
outputOptions(output, "map_pre_delta_bio", suspendWhenHidden = FALSE)
# Disable results tab until input$go is used
observeEvent(input$go == 1,{
if(input$go == 0){ #If true enable, else disable
js$disabletab("abc")
}else{
js$enabletab("abc")
}
})
### Remove old saved results if ANALYZE! is pressed again, so these results are not included in new reports
observeEvent(input$go, {
rvs$saved_bbox <- NULL
rvs$plot_comp_download_unscaled <- NULL
rvs$plot_comp_download_deltas <- NULL
rvs$plot_comp_download_scaled <- NULL
rvs$plot_temp_prec_realunscaled <- NULL
rvs$plot_gcm_pattern <- NULL
rvs$plot_delta_pattern <- NULL
rvs$plot_gcm_differences <- NULL
})
# Generate table of available GCMs
output$GCMs_table <- function(){
table_GCMs %>%
knitr::kable("html") %>%
kable_styling("striped", full_width = F)
}
##################################################
#### Scenario selection tab
##################################################
########### CODE FOR UI - RenderUI panels ###########
### Available GCMs - dynamically change
observe({
output$selection_gcms <- renderUI({
glue::glue("# Getting list of available GCMs") %>% message
scenarios <- list.files(paste0("clim_data/ccafs/rds"), pattern = input$res_sel) %>%
dplyr::as_tibble() %>%
magrittr::set_names("GCM") %>%
tidyr::separate(col = GCM, into = c("gcm_", "resolution_", "year_", "rcp_", "borrar"), sep = "\\.") %>% dplyr::select(-borrar) %>%
mutate(year_ = year_ %>% str_replace_all("year", ""),
rcp_ = rcp_ %>% str_replace_all("rcp", ""))
glue::glue("# - Available GCMs with current setting") %>% message
available_gcms <- scenarios %>%
filter(resolution_ == input$res_sel) %>%
filter(year_ == input$year_type) %>%
filter(rcp_ == input$rcp_type %>% str_replace("rcp", "")) %>%
pull(gcm_)
glue::glue("# - Generating GCMs options") %>% message
checkboxGroupInput(inputId = "sel_gcms", "",
inline = FALSE,
choices = available_gcms,
selected = available_gcms)
})
})
### DEFAULT SELECTED OPTIONS
observe({
n_gcms <- length(input$sel_gcms)
output$selected_gcms <- renderText(
glue::glue("{n_gcms} GCMs") %>% print()
)
print_rcp <- case_when(input$rcp_type == "rcp26" ~ "2.6",
input$rcp_type == "rcp45" ~ "4.5",
input$rcp_type == "rcp60" ~ "6.0",
input$rcp_type == "rcp85" ~ "8.5")
output$selected_scenario <- renderText(
glue::glue("Year {input$year_type}, RCP {print_rcp}, resolution: {input$res_sel}") %>% print()
)
type_selected_comparison <- case_when(input$compare_type == "bio_bio" ~ c("1 bioclim X 1 bioclim"),
input$compare_type == "bio_several" ~ "Multiple comparison")
output$selected_comparison <- renderText(
glue::glue("{type_selected_comparison}") %>% print()
)
})
# Hide unselection of GCMs (so it unfolds when clicked)
observeEvent(input$GCMs_button, {
if (input$GCMs_button %% 2 == 1){
shinyjs::hide(id = "selected_gcms", anim = T)
shinyjs::show(id = "selection_gcms", anim = T)
} else {
shinyjs::show(id = "selected_gcms", anim = T)
shinyjs::hide(id = "selection_gcms", anim = T)
}
})
# Hide Climate Change Scenario (so it unfolds when clicked)
observeEvent(input$CC_scenario, {
if (input$CC_scenario %% 2 == 1){
shinyjs::show(id = "year_type", anim = T)
shinyjs::show(id = "rcp_type", anim = T)
# shinyjs::show(id = "res_sel", anim = T)
shinyjs::hide(id = "selected_scenario", anim = T)
} else {
shinyjs::hide(id = "year_type", anim = T)
shinyjs::hide(id = "rcp_type", anim = T)
# shinyjs::hide(id = "res_sel", anim = T)
shinyjs::show(id = "selected_scenario", anim = T)
}
})
# Hide Type of comparison (so it unfolds when clicked)
observeEvent(input$Compar_type, {
if (input$Compar_type %% 2 == 1){
shinyjs::show(id = "compare_type", anim = T)
shinyjs::show(id = "compare_type_bio_bio", anim = T)
shinyjs::show(id = "compare_type_bio_several", anim = T)
shinyjs::hide(id = "selected_comparison", anim = T)
} else {
shinyjs::hide(id = "compare_type", anim = T)
shinyjs::hide(id = "compare_type_bio_bio", anim = T)
shinyjs::hide(id = "compare_type_bio_several", anim = T)
shinyjs::show(id = "selected_comparison", anim = T)
}
})
### List of bioclims to compare
# One to One comparison
output$compare_type_bio_bio <- renderUI({
conditionalPanel(condition = "input.compare_type == 'bio_bio'",
selectInput(inputId = "bio_bio_x",
label = "X axis",
choices = c("(bio 1) Annual Mean Temperature",
"(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))",
"(bio 3) Isothermality (BIO2/BIO7) (* 100)",
"(bio 4) Temperature Seasonality (standard deviation *100)",
"(bio 5) Max Temperature of Warmest Month",
"(bio 6) Min Temperature of Coldest Month",
"(bio 7) Temperature Annual Range (BIO5-BIO6)",
"(bio 8) Mean Temperature of Wettest Quarter",
"(bio 9) Mean Temperature of Driest Quarter",
"(bio 10) Mean Temperature of Warmest Quarter",
"(bio 11) Mean Temperature of Coldest Quarter",
"(bio 12) Annual Precipitation",
"(bio 13) Precipitation of Wettest Month",
"(bio 14) Precipitation of Driest Month",
"(bio 15) Precipitation Seasonality (Coefficient of Variation)",
"(bio 16) Precipitation of Wettest Quarter",
"(bio 17) Precipitation of Driest Quarter",
"(bio 18) Precipitation of Warmest Quarter",
"(bio 19) Precipitation of Coldest Quarter"),
multiple = FALSE,
selected = NULL),
selectInput(inputId = "bio_bio_y",
label = "Y axis",
choices = c("(bio 1) Annual Mean Temperature",
"(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))",
"(bio 3) Isothermality (BIO2/BIO7) (* 100)",
"(bio 4) Temperature Seasonality (standard deviation *100)",
"(bio 5) Max Temperature of Warmest Month",
"(bio 6) Min Temperature of Coldest Month",
"(bio 7) Temperature Annual Range (BIO5-BIO6)",
"(bio 8) Mean Temperature of Wettest Quarter",
"(bio 9) Mean Temperature of Driest Quarter",
"(bio 10) Mean Temperature of Warmest Quarter",
"(bio 11) Mean Temperature of Coldest Quarter",
"(bio 12) Annual Precipitation",
"(bio 13) Precipitation of Wettest Month",
"(bio 14) Precipitation of Driest Month",
"(bio 15) Precipitation Seasonality (Coefficient of Variation)",
"(bio 16) Precipitation of Wettest Quarter",
"(bio 17) Precipitation of Driest Quarter",
"(bio 18) Precipitation of Warmest Quarter",
"(bio 19) Precipitation of Coldest Quarter"),
multiple = FALSE,
selected = "(bio 12) Annual Precipitation"))
})
## Multiple comparisons
output$compare_type_bio_several <- renderUI({
conditionalPanel(condition = "input.compare_type == 'bio_several'",
selectInput(inputId = "bio_several_x",
label = "X axis",
choices = c("(bio 1) Annual Mean Temperature",
"(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))",
"(bio 3) Isothermality (BIO2/BIO7) (* 100)",
"(bio 4) Temperature Seasonality (standard deviation *100)",
"(bio 5) Max Temperature of Warmest Month",
"(bio 6) Min Temperature of Coldest Month",
"(bio 7) Temperature Annual Range (BIO5-BIO6)",
"(bio 8) Mean Temperature of Wettest Quarter",
"(bio 9) Mean Temperature of Driest Quarter",
"(bio 10) Mean Temperature of Warmest Quarter",
"(bio 11) Mean Temperature of Coldest Quarter",
"(bio 12) Annual Precipitation",
"(bio 13) Precipitation of Wettest Month",
"(bio 14) Precipitation of Driest Month",
"(bio 15) Precipitation Seasonality (Coefficient of Variation)",
"(bio 16) Precipitation of Wettest Quarter",
"(bio 17) Precipitation of Driest Quarter",
"(bio 18) Precipitation of Warmest Quarter",
"(bio 19) Precipitation of Coldest Quarter"),
multiple = TRUE,
selected = c("(bio 1) Annual Mean Temperature", "(bio 5) Max Temperature of Warmest Month")),
selectInput(inputId = "bio_several_y",
label = "Y axis",
choices = c("(bio 1) Annual Mean Temperature",
"(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))",
"(bio 3) Isothermality (BIO2/BIO7) (* 100)",
"(bio 4) Temperature Seasonality (standard deviation *100)",
"(bio 5) Max Temperature of Warmest Month",
"(bio 6) Min Temperature of Coldest Month",
"(bio 7) Temperature Annual Range (BIO5-BIO6)",
"(bio 8) Mean Temperature of Wettest Quarter",
"(bio 9) Mean Temperature of Driest Quarter",
"(bio 10) Mean Temperature of Warmest Quarter",
"(bio 11) Mean Temperature of Coldest Quarter",
"(bio 12) Annual Precipitation",
"(bio 13) Precipitation of Wettest Month",
"(bio 14) Precipitation of Driest Month",
"(bio 15) Precipitation Seasonality (Coefficient of Variation)",
"(bio 16) Precipitation of Wettest Quarter",
"(bio 17) Precipitation of Driest Quarter",
"(bio 18) Precipitation of Warmest Quarter",
"(bio 19) Precipitation of Coldest Quarter"),
multiple = TRUE,
selected = c("(bio 12) Annual Precipitation", "(bio 13) Precipitation of Wettest Month")))
})
#### MAP
### Leaflet interactive map
# create map
m <- leaflet(world_sf) %>%
addTiles() %>%
addProviderTiles("Esri.WorldPhysical", group = "Relieve") %>%
addTiles(options = providerTileOptions(noWrap = TRUE), group = "Countries") %>%
addLayersControl(baseGroups = c("Relieve", "Countries"),
options = layersControlOptions(collapsed = FALSE)) %>%
setView(0,0, zoom = 2) %>%
addDrawToolbar(targetGroup = 'draw',
singleFeature = TRUE,
rectangleOptions = filterNULL(list(
shapeOptions = drawShapeOptions(fillColor = "#8e113f",
color = "#595959"))),
polylineOptions = FALSE, polygonOptions = FALSE, circleOptions = FALSE,
circleMarkerOptions = FALSE, markerOptions = FALSE)#,
# editOptions = editToolbarOptions())
output$map <- renderLeaflet(m)
# Create map proxy to make further changes to existing map
map <- leafletProxy("map")
# Update the map depending on study area inputs and selections
observe({
# Extent selected by drawing rectangle
if (input$extent_type == "map_draw") {
map %>%
hideGroup("country") %>%
hideGroup("countrySel") %>%
hideGroup("biomes") %>%
hideGroup("biomesSel") %>%
hideGroup("ecorregions") %>%
hideGroup("ecorregionsSel") %>%
hideGroup("bbox") %>%
clearGroup("draw") %>%
showGroup("draw")
req(input$map_draw_new_feature)
# Get coordinates
coords <- unlist(input$map_draw_new_feature$geometry$coordinates)
xy <- matrix(c(coords[c(TRUE,FALSE)], coords[c(FALSE,TRUE)]), ncol = 2) %>%
unique %>%
extent
rvs$polySelXY <- xy
rvs$saved_bbox <- xy
}
# bounding-box extent
if (input$extent_type == 'map_bbox'){
req(input$xmin, input$xmax, input$ymin, input$ymax) # This stops it from failing while the number is being typed
map %>%
clearGroup("bbox") %>%
clearGroup("draw") %>%
clearGroup("biomes") %>%
clearGroup("biomesSel") %>%
clearGroup("ecorregions") %>%
clearGroup("ecorregionsSel") %>%
hideGroup("country") %>%
hideGroup("countrySel") %>%
# hideGroup("draw") %>%
hideGroup("biomes") %>%
hideGroup("biomesSel") %>%
hideGroup("ecorregions") %>%
hideGroup("ecorregionsSel") %>%
showGroup("bbox") %>%
addRectangles(group = "bbox",
lng1 = input$xmin,
lng2 = input$xmax,
lat1 = input$ymin,
lat2 = input$ymax,
weight = 1,
fillColor = "#1ebea6",
color = "#158b7a")
rvs$polySelXY <- extent(input$xmin,
input$xmax,
input$ymin,
input$ymax)
rvs$saved_bbox <- c(input$xmin, input$xmax, input$ymin, input$ymax)
}
# Countries selected by country name
if (input$extent_type == "map_country"){
# Country names manually added - subset layer to overlay
selected_countries <- world_sf %>%
filter(country %in% input$ext_name_country)
# Add polygons to leaflet
map %>%
clearGroup("draw") %>%
clearGroup("bbox") %>%
clearGroup("biomes") %>%
clearGroup("biomesSel") %>%
clearGroup("ecorregions") %>%
clearGroup("ecorregionsSel") %>%
clearGroup("countrySel") %>%
hideGroup("biomes") %>%
hideGroup("biomesSel") %>%
hideGroup("bbox") %>%
# hideGroup("draw") %>%
hideGroup("ecorregions") %>%
hideGroup("ecorregionsSel") %>%
showGroup("countrySel") %>%
showGroup("country") %>%
addPolygons(data = world_sf,
group = "country",
weight = 1,
fillOpacity = 0,
opacity = 0.5,
color = "#595959") %>%
addPolygons(data = selected_countries,
group = "countrySel",
weight = 1,
fillColor = "#8e113f",
fillOpacity = 0.4,
color = "#561a44")
rvs$polySelXY <- selected_countries
### Get coordinates for later use to crop and mask GCM rasters
req(input$map_draw_new_feature)
glue::glue("#> Crop Country layer to the extent drawn") %>% message
coords <- unlist(input$map_draw_new_feature$geometry$coordinates)
xy <- matrix(c(coords[c(TRUE,FALSE)], coords[c(FALSE,TRUE)]), ncol = 2) %>%
unique %>%
extent
glue::glue("#> Crop Countries to EXTENT {xy}") %>% message
selected_countries <- selected_countries %>%
st_crop(xmin = xmin(xy), xmax = xmax(xy), ymin = ymin(xy), ymax = ymax(xy))
rvs$saved_bbox <- c(xmin(xy), xmax(xy), ymin(xy), ymax(xy))
rvs$polySelXY <- selected_countries
}
# Countries selected by biome name
if (input$extent_type == "map_biomes"){
selected_biomes <- biomes %>%
filter(BIOME_NAME %in% input$ext_name_biomes)
# Add polygons to leaflet
map %>%
hideGroup("country") %>%
hideGroup("bbox") %>%
# hideGroup("draw") %>%
hideGroup("ecorregions") %>%
clearGroup("draw") %>%
clearGroup("country") %>%
clearGroup("countrySel") %>%
clearGroup("ecorregions") %>%
clearGroup("ecorregionsSel") %>%
clearGroup("biomesSel") %>%
showGroup("biomesSel") %>%
showGroup("biomes") %>%
addPolygons(data = biomes,
group = "biomes",
weight = 1,
fillOpacity = 0,
opacity = 0.5,
# smoothFactor = 3,
color = "#595959") %>%
# Highlight selected biomes
addPolygons(data = selected_biomes,
group = "biomesSel",
weight = 1,
fillColor = "#8e113f",
fillOpacity = 0.4,
color = "#561a44")
rvs$polySelXY <- selected_biomes
### Get coordinates for later use to crop and mask GCM rasters
req(input$map_draw_new_feature)
glue::glue("#> Crop biomes layer to the extent drawn") %>% message
coords <- unlist(input$map_draw_new_feature$geometry$coordinates)
xy <- matrix(c(coords[c(TRUE,FALSE)], coords[c(FALSE,TRUE)]), ncol = 2) %>%
unique %>%
extent
glue::glue("#> Crop biomes EXTENT {xy}") %>% message
selected_biomes <- selected_biomes %>%
st_crop(xmin = xmin(xy), xmax = xmax(xy), ymin = ymin(xy), ymax = ymax(xy))
rvs$saved_bbox <- c(xmin(xy), xmax(xy), ymin(xy), ymax(xy))
rvs$polySelXY <- selected_biomes
}
# Countries selected by ecorregion name
if (input$extent_type == "map_ecorregions"){
selected_ecorregions <- ecorregions %>%
filter(ECO_NAME %in% input$ext_name_ecorregions)
# Add polygons to leaflet
map %>%
hideGroup("country") %>%
hideGroup("bbox") %>%
hideGroup("biomes") %>%
clearGroup("draw") %>%
clearGroup("countrySel") %>%
clearGroup("biomesSel") %>%
showGroup("ecorregions") %>%
showGroup("ecorregionsSel") %>%
addPolygons(data = ecorregions,
group = "ecorregions",
weight = 1,
fillOpacity = 0,
opacity = 0.5,
# smoothFactor = 3,
color = "#595959") %>%
# Highlight selected ecorregions
addPolygons(data = selected_ecorregions,
group = "ecorregionsSel",
weight = 1,
fillColor = "#8e113f",
fillOpacity = 0.4,
color = "#561a44")
rvs$polySelXY <- selected_ecorregions
### Get coordinates for later use to crop and mask GCM rasters
req(input$map_draw_new_feature)
glue::glue("#> Crop ecorregions layer to the extent drawn") %>% message
coords <- unlist(input$map_draw_new_feature$geometry$coordinates)
xy <- matrix(c(coords[c(TRUE,FALSE)], coords[c(FALSE,TRUE)]), ncol = 2) %>%
unique %>%
extent
glue::glue("#> Crop ecorregions EXTENT {xy}") %>% message
selected_ecorregions <- selected_ecorregions %>%
st_crop(xmin = xmin(xy), xmax = xmax(xy), ymin = ymin(xy), ymax = ymax(xy))
rvs$saved_bbox <- c(xmin(xy), xmax(xy), ymin(xy), ymax(xy))
rvs$polySelXY <- selected_ecorregions
}
})
####################################################################################
#### RESULTS
####################################################################################
############### INTERNAL CALCULATIONS - COMPARISONS ###############
#### Comparison of GCMs and analyses ####
### Load raster data
reactive({
# When hidden options for GCM selection, consider some default to avoid errors
glue::glue("# DEF: Getting list of available GCMs") %>% message
scenarios <- list.files(paste0("clim_data/ccafs/rds"), pattern = input$res_sel) %>%
dplyr::as_tibble() %>%
magrittr::set_names("GCM") %>%
tidyr::separate(col = GCM, into = c("gcm_", "resolution_", "year_", "rcp_", "borrar"), sep = "\\.") %>% dplyr::select(-borrar) %>%
mutate(year_ = year_ %>% str_replace_all("year", ""),
rcp_ = rcp_ %>% str_replace_all("rcp", ""))
glue::glue("# - DEF: Available GCMs with current setting") %>% message
rvs$def_available_gcms <- scenarios %>%
filter(resolution_ == "10m") %>%
filter(year_ == "2070") %>%
filter(rcp_ == "45") %>%
pull(gcm_)
})
observeEvent(input$go, {
if (input$compare_type == "bio_bio"){
bio_vars_x <- input$bio_bio_x
bio_vars_y <- input$bio_bio_y
}
if (input$compare_type == "bio_several"){
bio_vars_x <- input$bio_several_x
bio_vars_y <- input$bio_several_y
}
# Translate to regular names
bio_vars_x2 <- case_when(bio_vars_x == "(bio 1) Annual Mean Temperature" ~ "bio_1",
bio_vars_x == "(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))" ~ "bio_2",
bio_vars_x == "(bio 3) Isothermality (BIO2/BIO7) (* 100)" ~ "bio_3",
bio_vars_x == "(bio 4) Temperature Seasonality (standard deviation *100)" ~ "bio_4",
bio_vars_x == "(bio 5) Max Temperature of Warmest Month" ~ "bio_5",
bio_vars_x == "(bio 6) Min Temperature of Coldest Month" ~ "bio_6",
bio_vars_x == "(bio 7) Temperature Annual Range (BIO5-BIO6)" ~ "bio_7",
bio_vars_x == "(bio 8) Mean Temperature of Wettest Quarter" ~ "bio_8",
bio_vars_x == "(bio 9) Mean Temperature of Driest Quarter" ~ "bio_9",
bio_vars_x == "(bio 10) Mean Temperature of Warmest Quarter" ~ "bio_10",
bio_vars_x == "(bio 11) Mean Temperature of Coldest Quarter" ~ "bio_11",
bio_vars_x == "(bio 12) Annual Precipitation" ~ "bio_12",
bio_vars_x == "(bio 13) Precipitation of Wettest Month" ~ "bio_13",
bio_vars_x == "(bio 14) Precipitation of Driest Month" ~ "bio_14",
bio_vars_x == "(bio 15) Precipitation Seasonality (Coefficient of Variation)" ~ "bio_15",
bio_vars_x == "(bio 16) Precipitation of Wettest Quarter" ~ "bio_16",
bio_vars_x == "(bio 17) Precipitation of Driest Quarter" ~ "bio_17",
bio_vars_x == "(bio 18) Precipitation of Warmest Quarter" ~ "bio_18",
bio_vars_x == "(bio 19) Precipitation of Coldest Quarter" ~ "bio_19")
bio_vars_y2 <- case_when(bio_vars_y == "(bio 1) Annual Mean Temperature" ~ "bio_1",
bio_vars_y == "(bio 2) Mean Diurnal Range (Mean of monthly (max temp - min temp))" ~ "bio_2",
bio_vars_y == "(bio 3) Isothermality (BIO2/BIO7) (* 100)" ~ "bio_3",
bio_vars_y == "(bio 4) Temperature Seasonality (standard deviation *100)" ~ "bio_4",
bio_vars_y == "(bio 5) Max Temperature of Warmest Month" ~ "bio_5",
bio_vars_y == "(bio 6) Min Temperature of Coldest Month" ~ "bio_6",
bio_vars_y == "(bio 7) Temperature Annual Range (BIO5-BIO6)" ~ "bio_7",
bio_vars_y == "(bio 8) Mean Temperature of Wettest Quarter" ~ "bio_8",
bio_vars_y == "(bio 9) Mean Temperature of Driest Quarter" ~ "bio_9",
bio_vars_y == "(bio 10) Mean Temperature of Warmest Quarter" ~ "bio_10",
bio_vars_y == "(bio 11) Mean Temperature of Coldest Quarter" ~ "bio_11",
bio_vars_y == "(bio 12) Annual Precipitation" ~ "bio_12",
bio_vars_y == "(bio 13) Precipitation of Wettest Month" ~ "bio_13",
bio_vars_y == "(bio 14) Precipitation of Driest Month" ~ "bio_14",
bio_vars_y == "(bio 15) Precipitation Seasonality (Coefficient of Variation)" ~ "bio_15",
bio_vars_y == "(bio 16) Precipitation of Wettest Quarter" ~ "bio_16",
bio_vars_y == "(bio 17) Precipitation of Driest Quarter" ~ "bio_17",
bio_vars_y == "(bio 18) Precipitation of Warmest Quarter" ~ "bio_18",
bio_vars_y == "(bio 19) Precipitation of Coldest Quarter" ~ "bio_19")
rvs$bio_vars_x2 <- bio_vars_x2
rvs$bio_vars_x_full <- bio_vars_x
rvs$bio_vars_y2 <- bio_vars_y2
rvs$bio_vars_y_full <- bio_vars_y
rvs$bio_vars_all <- c(bio_vars_x2, bio_vars_y2)
})
########### RESULTS: CALCULATIONS WITH RASTER DATA ############
observeEvent(input$go, {
withProgress(message = 'Loading climatic data',
detail = NULL,
value = 0, {
incProgress(amount = 0.1, message = 'Loading climatic data')
### Load variables
glue::glue("#>> Loading climatic data") %>% message
if(!is.null(input$sel_gcms)){
# Load .tif data
clim_vars_files <- paste0(input$sel_gcms, ".",
input$res_sel,
".year", input$year_type, ".",
input$rcp_type) %>%
purrr::map(~list.files("clim_data/ccafs/raw_rasters/",
pattern = .x,
full.names = T)) %>%
purrr::map(~ raster::stack(.x))
clim_vars_files <- clim_vars_files %>%
purrr::map(~setNames(.x, names(.x) %>% gsub(".*\\.bio","",.) %>% paste0("bio",.)))
# Load .rds data
# clim_vars_files <- paste0("clim_data/ccafs/rds/",
# input$sel_gcms, ".",
# input$res_sel,
# ".year", input$year_type, ".",
# input$rcp_type,
# ".rds") %>%
# purrr::map(~ readRDS(.x))
} else {
# Load .tif data
clim_vars_files <- paste0(rvs$def_available_gcms, ".",
input$res_sel,
".year", input$year_type, ".",
input$rcp_type) %>%
purrr::map(~list.files("clim_data/ccafs/raw_rasters/",
pattern = .x,
full.names = T)) %>%
purrr::map(~ raster::stack(.x))
clim_vars_files <- clim_vars_files %>%
purrr::map(~setNames(.x, names(.x) %>% gsub(".*\\.bio","",.) %>% paste0("bio",.)))
# Load .rds data
# clim_vars_files <- paste0("clim_data/ccafs/rds/",
# rvs$def_available_gcms, ".",
# input$res_sel,
# ".year", input$year_type, ".",
# input$rcp_type,
# ".rds") %>%
# purrr::map(~ readRDS(.x))
}
rvs$clim_vars_complete <- clim_vars_files %>%
magrittr::set_names(input$sel_gcms)
# Select a subset of bioclim variables
incProgress(amount = 0.1, message = "Dropping unnecessary layers")
glue::glue("#>> Subsetting selected variables") %>% message
rvs$clim_vars <- rvs$clim_vars_complete %>%
purrr::map(~ raster::subset(.x, subset = c(rvs$bio_vars_x2, rvs$bio_vars_y2)))
# Crop to study area
incProgress(amount = 0.1, message = "Cropping to study area")
req(rvs$polySelXY)
glue::glue("#>> Cropping to study area") %>% message()
## When it is not a polygon
if (!is(rvs$polySelXY, "sf")){
rvs$clim_vars <- rvs$clim_vars %>%
purrr::map(~ raster::crop(.x, rvs$polySelXY))
# Save a copy of croped countries
rvs$sf_country <- world_sf %>%
st_crop(xmin = xmin(rvs$polySelXY), xmax = xmax(rvs$polySelXY), ymin = ymin(rvs$polySelXY), ymax = ymax(rvs$polySelXY))
}
## When it is a polygon
if (is(rvs$polySelXY, "sf")){
glue::glue("# - Rasterizing polygon") %>% message
rvs$polySelXY <- rvs$polySelXY %>%
mutate(id = 1) %>% group_by(id) %>% summarise
rvs$polySelXY_r <- fasterize::fasterize(rvs$polySelXY,
rvs$clim_vars[[1]][[1]] %>%
raster::crop(extent(xmin(extent(rvs$polySelXY)),
xmax(extent(rvs$polySelXY)),
ymin(extent(rvs$polySelXY)),
ymax(extent(rvs$polySelXY)))))
glue::glue("# - Masking") %>% message
rvs$clim_vars <- rvs$clim_vars %>%
purrr::map(~ raster::crop(.x, rvs$polySelXY_r)) %>%
purrr::map(~ raster::mask(.x, rvs$polySelXY_r))
# Save a copy of croped countries
rvs$sf_country <- rvs$polySelXY
}
### Divide by 10 some temperature layers to use common units
glue::glue("#>> Transforming temperature layers to regular units of ºC") %>% message
for (i in 1:length(rvs$clim_vars)){
for (j in names(rvs$clim_vars[[i]])[names(rvs$clim_vars[[i]]) %in% c("bio_1", "bio_2", "bio_4", "bio_5", "bio_6", "bio_7", "bio_8", "bio_9", "bio_10", "bio_11")]){
rvs$clim_vars[[i]][[j]] <- rvs$clim_vars[[i]][[j]] / 10
}
}
## Difference with ensemble of future projections
### Compare each GCM with baseline
incProgress(amount = 0.3, message = "Comparing GCMs with baseline")
glue::glue("#>> Loading and preparing baseline") %>% message
# Load baseline
## Loading .tif data
rvs$clim_baseline_complete <- paste0("clim_data/baseline/raw_rasters/baseline.", input$res_sel, ".bio_", 1:19, ".tif") %>%
stack %>%
setNames(names(.) %>% gsub(".*\\.bio","",.) %>% paste0("bio",.))
## Loading .rds data
# rvs$clim_baseline_complete <- readRDS(paste0("clim_data/baseline/rds/baseline.", input$res_sel, ".rds"))
rvs$clim_baseline <- rvs$clim_baseline_complete %>%
crop(extent(rvs$clim_vars[[1]][[1]])) %>%
mask(rvs$clim_vars[[1]][[1]])
glue::glue("#>> Subsetting bioclims in baseline") %>% message
rvs$clim_baseline <- rvs$clim_baseline %>%
raster::subset(c(rvs$bio_vars_x2, rvs$bio_vars_y2))
for (j in names(rvs$clim_baseline)[names(rvs$clim_baseline) %in% c("bio_1", "bio_2", "bio_4", "bio_5", "bio_6", "bio_7", "bio_8", "bio_9", "bio_10", "bio_11")]){
rvs$clim_baseline[[j]] <- rvs$clim_baseline[[j]] / 10
}
### Calculate differences to baseline
glue::glue("#>> Comparing GCMs with baseline") %>% message
rvs$clim_delta <- rvs$clim_vars %>%
purrr::map(~ .x - rvs$clim_baseline)
### Create a map of percentage of differences
rvs$clim_deltaperc <- rvs$clim_vars %>%
purrr::map(~ 100 * (.x - rvs$clim_baseline) / rvs$clim_baseline)
## Difference with ensemble of future projections
### Calculate ensemble of GCMs
incProgress(amount = 0.3, message = "Calculating mean ensemble")
glue::glue("#>> Calculating the ensemble from all different GCM projections") %>% message
rvs$clim_ens <- rvs$clim_vars %>%
purrr::reduce(`+`) %>% # Sum all layers
raster::calc(fun = function(x){x / length(rvs$clim_vars)}) # Divide by the number of layers
rvs$clim_delta_ensemble <- rvs$clim_ens - rvs$clim_baseline
### Compare each GCM with the ensemble
incProgress(amount = 0.3, message = "Computing differences with ensemble")
glue::glue("#>> Computing differences between each GCM and the GCM ensemble") %>% message
rvs$clim_diff <- rvs$clim_vars %>%
purrr::map(~ .x - rvs$clim_ens)
### Create a map of percentage of differences with ensemble
rvs$clim_diffperc <- rvs$clim_vars %>%
purrr::map(~ 100 * (.x - rvs$clim_ens) / rvs$clim_ens)
})
})
################## RESULTS: SCATTERPLOTs ##################
observeEvent({#input$type_scaled
# input$type_scaled_pre_delta
input$go
}, {
req(rvs$clim_ens)
withProgress(message = 'Comparing GCM values',
detail = NULL,
value = 0, {
# req(input$go)
# req(input$type_scaled)
##### Axis and column labels
if(input$compare_type == "bio_bio"){
rvs$xaxis_lab <- case_when(rvs$bio_vars_x2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_x_full, " (ºC)"),
rvs$bio_vars_x2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_x_full, " (mm)"),
rvs$bio_vars_x2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_x2, ""))
rvs$yaxis_lab <- case_when(rvs$bio_vars_y2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_y_full, " (ºC)"),
rvs$bio_vars_y2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_y_full, " (mm)"),
rvs$bio_vars_y2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_y2, ""))
}
if(input$compare_type == "bio_several"){
rvs$xaxis_lab <- paste0(rvs$bio_vars_x2, collapse = " - ")
rvs$yaxis_lab <- paste0(rvs$bio_vars_y2, collapse = " - ")
}
if(input$compare_type == "bio_bio"){
rvs$xcol_sc_lab <- paste0(rvs$bio_vars_x2, "(scaled)")
rvs$ycol_sc_lab <- paste0(rvs$bio_vars_y2, "(scaled)")
rvs$xcol_unsc_lab <- case_when(rvs$bio_vars_x2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_x2, " (ºC)"),
rvs$bio_vars_x2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_x2, " (mm)"),
rvs$bio_vars_x2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_x2, ""))
rvs$ycol_unsc_lab <- case_when(rvs$bio_vars_y2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_y2, " (ºC)"),
rvs$bio_vars_y2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_y2, " (mm)"),
rvs$bio_vars_y2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_y2, ""))
rvs$xcol_delta_lab <- case_when(rvs$bio_vars_x2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_x2, " (ºC) - delta"),
rvs$bio_vars_x2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_x2, " (mm) - delta"),
rvs$bio_vars_x2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_x2, " - delta"))
rvs$ycol_delta_lab <- case_when(rvs$bio_vars_y2 %in% paste0("bio_", c(1:2, 5:11)) ~ paste0(rvs$bio_vars_y2, " (ºC) - delta"),
rvs$bio_vars_y2 %in% paste0("bio_", c(12:19)) ~ paste0(rvs$bio_vars_y2, " (mm) - delta"),
rvs$bio_vars_y2 %in% paste0("bio_", c(3:4)) ~ paste0(rvs$bio_vars_y2, " - delta"))
}
if(input$compare_type == "bio_several"){
rvs$xcol_sc_lab <- paste0(rvs$bio_vars_x2, collapse = " - ")
rvs$ycol_sc_lab <- paste0(rvs$bio_vars_y2, collapse = " - ")
rvs$xcol_unsc_lab <- paste0(rvs$bio_vars_x2, collapse = " - ")
rvs$ycol_unsc_lab <- paste0(rvs$bio_vars_y2, collapse = " - ")
rvs$xcol_delta_lab <- paste0(paste0(rvs$bio_vars_x2, collapse = " - "), "(delta)")
rvs$ycol_delta_lab <- paste0(paste0(rvs$bio_vars_y2, collapse = " - "), "(delta)")
}
########### COMPARE GCMs
glue::glue("#>>> Computing differences between GCMs in temperature and precipitation") %>% message()
### Table of differences
# Convert rasters to a table with values
glue::glue("# Creating table of differences") %>% message()
############################## Scaled ##############################
table_diff_scaled <- list()
for (v in names(rvs$clim_vars[[1]])){
temp_table <- rvs$clim_vars %>%
purrr::map(~ .x[[v]]) %>%
purrr::map_dfc(~ raster::values(.x)) %>% t() %>%
scale()
temp_table <- temp_table %>%
as.data.frame() %>%
tibble::rownames_to_column("GCM") %>%
tibble::as_tibble()
table_diff_scaled[[length(table_diff_scaled) + 1]] <- temp_table
names(table_diff_scaled)[length(table_diff_scaled)] <- v
}
# Calculare means for each GCM and combine in one unique table
table_diff_scaled <- table_diff_scaled %>%
purrr::map_dfc(~ rowMeans(.x[,2:ncol(.x)], na.rm = T)) %>%
dplyr::bind_cols(table_diff_scaled[[1]][,1])
# Combine temperature and precipitation variables separatedly
table_scaled <- tibble::tibble(GCM = table_diff_scaled %>%
dplyr::select(GCM) %>% dplyr::pull(GCM),
x_axis = table_diff_scaled %>%
dplyr::select(rvs$bio_vars_x2) %>%
rowMeans(na.rm = T),
y_axis = table_diff_scaled %>%
dplyr::select(rvs$bio_vars_y2) %>%
rowMeans(na.rm = T)) %>%
dplyr::mutate(Distance = raster::pointDistance(c(0, 0),
.[,2:3],
lonlat = FALSE)) %>%
dplyr::arrange(Distance)
## Is within confidence intervals?
# std_error <- mean(table_scaled$Distance) + sd(table_scaled$Distance)/sqrt(nrow(table_scaled))
std_error <- mean(table_scaled$Distance) + 2*sd(table_scaled$Distance)
table_scaled <- table_scaled %>%
dplyr::mutate(Within_circle = ifelse(Distance <= std_error, TRUE, FALSE))
rvs$table_scaled <- table_scaled
# Prepare circle for plot
circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){r = diameter / 2
tt <- seq(0,2*pi,length.out = npoints)
xx <- center[1] + r * cos(tt)
yy <- center[2] + r * sin(tt)
return(data.frame(x = xx, y = yy))}
circle <- circleFun(center = c(0,0), diameter = std_error * 2, npoints = 300)
############################## Real unscaled ##############################
table_diff_realunscaled <- list()
for (v in names(rvs$clim_diff[[1]])){
temp_table <- rvs$clim_diff %>%
purrr::map(~ .x[[v]]) %>%
purrr::map_dfc(~ raster::values(.x)) %>% t()
temp_table <- temp_table %>%
as.data.frame() %>%
tibble::rownames_to_column("GCM") %>%
tibble::as_tibble()
table_diff_realunscaled[[length(table_diff_realunscaled) + 1]] <- temp_table
names(table_diff_realunscaled)[length(table_diff_realunscaled)] <- v
}
# Calculare means for each GCM and combine in one unique table
table_diff_realunscaled <- table_diff_realunscaled %>%
purrr::map_dfc(~ rowMeans(.x[,2:ncol(.x)], na.rm = T)) %>%
dplyr::bind_cols(table_diff_realunscaled[[1]][,1])
# Combine temperature and precipitation variables separatedly
table_realunscaled <- tibble::tibble(GCM = table_diff_realunscaled %>%
dplyr::select(GCM) %>% dplyr::pull(GCM),
x_axis = table_diff_realunscaled %>%
dplyr::select(rvs$bio_vars_x2) %>%
rowMeans(na.rm = T),
y_axis = table_diff_realunscaled %>%
dplyr::select(rvs$bio_vars_y2) %>%
rowMeans(na.rm = T)) %>%
dplyr::mutate(Distance = raster::pointDistance(c(0, 0),
.[,2:3],
lonlat = FALSE))
rvs$table_realunscaled <- table_realunscaled
#############################################################################
############################## Unscaled ##############################
rvs$clim_vars_uns <- rvs$clim_vars
rvs$clim_vars_uns[[length(rvs$clim_vars_uns) + 1]] <- rvs$clim_baseline
names(rvs$clim_vars_uns)[length(rvs$clim_vars_uns)] <- "BASELINE"
rvs$clim_vars_uns[[length(rvs$clim_vars_uns) + 1]] <- rvs$clim_ens
names(rvs$clim_vars_uns)[length(rvs$clim_vars_uns)] <- "ENSEMBLE"
table_diff_unscaled <- list()
for (v in names(rvs$clim_vars_uns[[1]])){
temp_table <- rvs$clim_vars_uns %>%
purrr::map(~ .x[[v]]) %>%
purrr::map_dfc(~ raster::values(.x)) %>% t()
temp_table <- temp_table %>%
as.data.frame() %>%
tibble::rownames_to_column("GCM") %>%
tibble::as_tibble()
table_diff_unscaled[[length(table_diff_unscaled) + 1]] <- temp_table
names(table_diff_unscaled)[length(table_diff_unscaled)] <- v
}
# Calculare means for each GCM and combine in one unique table
table_diff_unscaled <- table_diff_unscaled %>%
purrr::map_dfc(~ rowMeans(.x[,2:ncol(.x)], na.rm = T)) %>%
dplyr::bind_cols(table_diff_unscaled[[1]][,1])
# Combine temperature and precipitation variables separatedly
table_unscaled <- tibble::tibble(GCM = table_diff_unscaled %>%
dplyr::select(GCM) %>% dplyr::pull(GCM),
x_axis = table_diff_unscaled %>%
dplyr::select(rvs$bio_vars_x2) %>%
rowMeans(na.rm = T),
y_axis = table_diff_unscaled %>%
dplyr::select(rvs$bio_vars_y2) %>%
rowMeans(na.rm = T)) %>%
dplyr::mutate(Distance = raster::pointDistance(c(0, 0),
.[,2:3],
lonlat = FALSE)) %>%
dplyr::arrange(Distance)
rvs$table_unscaled <- table_unscaled
############################## Deltas ##############################
rvs$clim_delta2 <- rvs$clim_delta