-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDOMin_Mean_Range_trends.Rmd
819 lines (602 loc) · 25.9 KB
/
DOMin_Mean_Range_trends.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
---
title: "Assessing Climate Change Effects in VA Reservoirs"
subtitle: "Part 3: Deriving Trends for Dissolved Oxygen (DOMax, DOMin, DOMean, DORange)"
author: "Andrew Cameron"
output:
html_document:
toc: true
toc_depth: 4
toc_float: true
---
```{r setup, include=TRUE, warning=FALSE, message=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# Install any missing packages
install_packages <- function(packages) {
new_packages <- packages[!(packages %in% installed.packages()[,"Package"])]
if(length(new_packages) > 0) {
install.packages(new_packages, dependencies = TRUE)
}
}
packages <- c("ggplot2", "tidyverse", "mblm")
install_packages(packages)
library(ggplot2)
library(tidyverse)
library(mblm)
```
## Data Preprocessing
```{r `read in data`}
trendSites.df <- openxlsx::read.xlsx("input_data/data_original.xlsx", sheet = 2)
allData.df <- openxlsx::read.xlsx("input_data/data_original.xlsx", sheet = 3)
# Convert `date` column from Excel encoded date to a more legible date format. Otherwise date shows as numeric value, e.g. '44230'.
allData.df$Date <- allData.df$Date * 86400 # 86400 = seconds in a day.
allData.df$Date <- as.POSIXct(allData.df$Date, origin = "1899-12-30", tz = "UTC")
```
```{r 'remove anomlies'}
# a surface temperature (Tmax) of 2.8 C in August
# 13774 6ACNR000.00 8/28/1990 0.3 NA NA NA NA
which(grepl("13774", allData.df$X1))
allData.df[13770, (5:8)] <- NA
```
```{r `subset and filter data`}
station_IDS <- trendSites.df$FDT_STA_ID
excluded_sites <- c("2-JKS053.48",
"2-XDD000.40",
"4AROA192.55",
"4AROA196.05",
"5ASRN000.66",
"6ACNR000.00",
"6APNR008.15") # only surface water measurements ever taken
# subset 34 trend sites (41 - 7 excluded)
trendsites <- allData.df %>%
mutate(MonthNum = lubridate::month(Date),
Year = lubridate::year(Date)) %>%
filter(FDT_STA_ID %in% station_IDS) %>%
filter(!FDT_STA_ID %in% excluded_sites) %>%
filter(MonthNum %in% 5:10)
# apply filters (based on 'Filter' column in "Station Specific Trend Sites.xlsx")
specialFiltersNeeded <- c("4ABWR017.42", "4AROA038.49", "4AROA192.94", "9-NEW098.32", "9-PKC004.16")
special1 <- trendsites %>%
filter(FDT_STA_ID == "4ABWR017.42") %>%
filter(MaxDepth.x >= 5)
special2 <- trendsites %>%
filter(FDT_STA_ID == "4AROA038.49") %>%
filter(MaxDepth.x >= 6)
special3 <- trendsites %>%
filter(FDT_STA_ID == "4AROA192.94") %>%
filter(MaxDepth.x >= 3)
special4 <- trendsites %>%
filter(FDT_STA_ID == "9-NEW098.32") %>%
filter(MaxDepth.x >= 6)
special5 <- trendsites %>%
filter(FDT_STA_ID == "9-PKC004.16") %>%
filter(MaxDepth.x >= 3)
sites_less85max <- trendsites %>%
filter(!FDT_STA_ID %in% specialFiltersNeeded) %>%
filter(MaxDepth.x >= .85*MeanDepth)
# Bring back into single df
subset.df <- rbind(sites_less85max, special1, special2, special3, special4, special5)
# "add additional filter excluding trend results for profiles where NObs<10 (I count there are ~7 of these)"
# applying this filter to the df for deriving trends (`subset.df`) complicates the code substantially because it results in there not being a corresponding MonthNum 5:10 for each station ID. Filter applied after the trends are derived but before plotting.
countPerGroup <- subset.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarise(Nobs = n()) %>%
mutate(key = paste(FDT_STA_ID, MonthNum, sep="_"))
insufficient_Nobs <- countPerGroup %>%
filter(Nobs < 10)
insufficient_Nobs <- insufficient_Nobs$key
```
## Minimum Dissovled Oxygen
```{r `derive DOMin by month` }
monthlyDOMin <- subset.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarize(Mean = mean(DOMin, na.rm = TRUE),
Min = min(DOMin, na.rm = TRUE),
Max = max(DOMin, na.rm = TRUE),
Nobs = n(),
.groups = 'drop') %>%
mutate(Month = month.name[MonthNum])
# write_csv(monthlyDOMin, "output_data/DOMin_stats_monthlyByStation.csv")
cols_to_keep <- colnames(subset.df)
df.DOMin <- subset.df %>%
left_join(monthlyDOMin, by = c("FDT_STA_ID", "MonthNum")) %>%
select(all_of(cols_to_keep), Mean)
```
```{r `DOMin fit regressions for each month-station`, warning=FALSE}
# fit a linear regression for DOMean vs. year by month-station using the mblm function (median based linear model) as this is thought to be less sensitive to outliers.
#Usage
#mblm(formula, dataframe, repeated = TRUE)
#Arguments
#formula A formula of type y ~ x (only linear models are accepted)
#dataframe Optional dataframe
#repeated If set to true, model is computed using repeated medians. If false, a single median estimators are calculated
# remove NA values -- mblm() does not handle NA as lm() does
df.DOMin <- df.DOMin %>%
filter(!is.na(DOMin))
# create list to store regression results
modelSummaries <- list()
for (station_id in unique(df.DOMin$FDT_STA_ID)) {
for (month_num in 5:10) {
month_station <- df.DOMin %>%
filter(FDT_STA_ID == station_id & MonthNum == month_num)
model <- mblm(DOMin ~ Year, data = month_station)
mod.sum <- summary.mblm(model)
# store results
modelSummaries[[paste(station_id, month_num, sep = "_")]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year", "MAD"] ,
pvalue = mod.sum$coefficients["Year", 4],
intercept = mod.sum$coefficients[1,1]
)
}
}
## --------DOMin, with 1975 as y intercept-------------
q <- df.DOMin %>%
mutate(Year1975 = Year - 1975) %>%
filter(MonthNum == 8)
modelSummaries_DOMin1975 <- list()
for (station_id in unique(q$FDT_STA_ID)) {
data = subset(q, FDT_STA_ID == station_id)
model <- mblm(DOMin ~ Year1975, data = data)
mod.sum <- summary.mblm(model)
# store results
modelSummaries_DOMin1975[[paste(station_id)]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year1975", "MAD"] ,
pvalue = mod.sum$coefficients["Year1975", 4],
intercept = mod.sum$coefficients[1,1]
)
}
# mblm does not return a standard error. Instead, summary.mblm can be used to extract the MAD or Median Absolute Deviation." It's a robust measure of variability that is less sensitive to outliers than the standard deviation, which is commonly used in traditional statistical analyses.
```
```{r `DOMin add reg stats to summary df`}
# create station-month key
monthlyDOMin <- monthlyDOMin %>%
mutate( key = paste(FDT_STA_ID, MonthNum, sep="_"),
model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA)
for (i in 1:nrow(monthlyDOMin)) {
key = monthlyDOMin$key[i]
monthlyDOMin$model_slope[i] <- modelSummaries[[key]]$slope
monthlyDOMin$model_MAD[i] <- modelSummaries[[key]]$MAD
monthlyDOMin$model_pval[i] <- modelSummaries[[key]]$pvalue
monthlyDOMin$model_intercept[i] <- modelSummaries[[key]]$intercept
}
DOMin_final <- monthlyDOMin %>%
filter(!key %in% insufficient_Nobs)
#--------------------------------------------
# reg stats for August DOMin non-normalized with 1975 as y intercept
monthly_DOMin1975 <- monthlyDOMin %>%
mutate( model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA) %>%
filter(MonthNum == 8)
for (i in 1:nrow(monthly_DOMin1975)) {
key = monthly_DOMin1975$FDT_STA_ID[i]
monthly_DOMin1975$model_slope[i] <- modelSummaries_DOMin1975[[key]]$slope
monthly_DOMin1975$model_MAD[i] <- modelSummaries_DOMin1975[[key]]$MAD
monthly_DOMin1975$model_pval[i] <- modelSummaries_DOMin1975[[key]]$pvalue
monthly_DOMin1975$model_intercept[i] <- modelSummaries_DOMin1975[[key]]$intercept
}
DOMin1975_final <- monthly_DOMin1975 %>%
filter(!key %in% insufficient_Nobs)
#------------------------------------------------
write_csv(DOMin_final, "output_data/DOMin_mblmModelStatistics.csv")
# do any month-stations return a 0 slope with sig pval? In this case, no
wonky_results <- DOMin_final %>%
filter(model_slope == 0 & model_pval <= 0.05)
paste(nrow(wonky_results), "station-months returned a slope of 0 with a significant p-value in DOMin trend analysis.", sep=" ")
```
## Mean Dissovled Oxygen
```{r `derive DOMean by month` }
monthlyDOMean <- subset.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarize(Mean = mean(DOMean, na.rm = TRUE),
Min = min(DOMean, na.rm = TRUE),
Max = max(DOMean, na.rm = TRUE),
Nobs = n(),
.groups = 'drop') %>%
mutate(Month = month.name[MonthNum])
# write_csv(monthlyDOMean, "output_data/DOMean_stats_monthlyByStation.csv")
cols_to_keep <- colnames(subset.df)
df.DOMean <- subset.df %>%
left_join(monthlyDOMean, by = c("FDT_STA_ID", "MonthNum")) %>%
select(all_of(cols_to_keep), Mean)
```
```{r `DOMean fit regressions for each month-station`, warning = FALSE}
# fit a linear regression for DOMean vs. year by month-station using the mblm function (median based linear model) as this is thought to be less sensitive to outliers.
#Usage
#mblm(formula, dataframe, repeated = TRUE)
#Arguments
#formula A formula of type y ~ x (only linear models are accepted)
#dataframe Optional dataframe
#repeated If set to true, model is computed using repeated medians. If false, a single median estimators are calculated
# remove NA values -- mblm() does not handle NA as lm() does
df.DOMean <- df.DOMean %>%
filter(!is.na(DOMean))
# create list to store regression results
modelSummaries <- list()
for (station_id in unique(df.DOMean$FDT_STA_ID)) {
for (month_num in 5:10) {
month_station <- df.DOMean %>%
filter(FDT_STA_ID == station_id & MonthNum == month_num)
model <- mblm(DOMean ~ Year, data = month_station)
mod.sum <- summary.mblm(model)
# store results
modelSummaries[[paste(station_id, month_num, sep = "_")]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year", "MAD"] ,
pvalue = mod.sum$coefficients["Year", 4],
intercept = mod.sum$coefficients[1,1]
)
}
}
## --------DOMin, with 1975 as y intercept-------------
q <- df.DOMean %>%
mutate(Year1975 = Year - 1975) %>%
filter(MonthNum == 8)
modelSummaries_DOMean1975 <- list()
for (station_id in unique(q$FDT_STA_ID)) {
data = subset(q, FDT_STA_ID == station_id)
model <- mblm(DOMean ~ Year1975, data = data)
mod.sum <- summary.mblm(model)
# store results
modelSummaries_DOMean1975[[paste(station_id)]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year1975", "MAD"] ,
pvalue = mod.sum$coefficients["Year1975", 4],
intercept = mod.sum$coefficients[1,1]
)
}
# mblm does not return a standard error. Instead, summary.mblm can be used to extract the MAD or Median Absolute Deviation." It's a robust measure of variability that is less sensitive to outliers than the standard deviation, which is commonly used in traditional statistical analyses.
```
```{r `DOMean add reg stats to summary df`}
# create station-month key
monthlyDOMean <- monthlyDOMean %>%
mutate( key = paste(FDT_STA_ID, MonthNum, sep="_"),
model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA)
for (i in 1:nrow(monthlyDOMean)) {
key = monthlyDOMean$key[i]
monthlyDOMean$model_slope[i] <- modelSummaries[[key]]$slope
monthlyDOMean$model_MAD[i] <- modelSummaries[[key]]$MAD
monthlyDOMean$model_pval[i] <- modelSummaries[[key]]$pvalue
monthlyDOMean$model_intercept[i] <- modelSummaries[[key]]$intercept
}
DOMean_final <- monthlyDOMean %>%
filter(!key %in% insufficient_Nobs)
#--------------------------------------------
# reg stats for August DOMean non-normalized with 1975 as y intercept
monthly_DOMean1975 <- monthlyDOMean %>%
mutate( model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA) %>%
filter(MonthNum == 8)
for (i in 1:nrow(monthly_DOMean1975)) {
key = monthly_DOMean1975$FDT_STA_ID[i]
monthly_DOMean1975$model_slope[i] <- modelSummaries_DOMean1975[[key]]$slope
monthly_DOMean1975$model_MAD[i] <- modelSummaries_DOMean1975[[key]]$MAD
monthly_DOMean1975$model_pval[i] <- modelSummaries_DOMean1975[[key]]$pvalue
monthly_DOMean1975$model_intercept[i] <- modelSummaries_DOMean1975[[key]]$intercept
}
DOMean1975_final <- monthly_DOMean1975 %>%
filter(!key %in% insufficient_Nobs)
#------------------------------------------------
write_csv(DOMean_final, "output_data/DOMean_mblmModelStatistics.csv")
# do any month-stations return a 0 slope with sig pval? In this case, no
wonky_results <- DOMean_final %>%
filter(model_slope == 0 & model_pval <= 0.05)
paste(nrow(wonky_results), "station-months returned a slope of 0 with a significant p-value in DOMean trend analysis.", sep=" ")
```
## Dissovled Oxygen Range
```{r `derive DORange by month` }
monthlyDORange <- subset.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarize(Mean = mean(DORange, na.rm = TRUE),
Min = min(DORange, na.rm = TRUE),
Max = max(DORange, na.rm = TRUE),
Nobs = n(),
.groups = 'drop') %>%
mutate(Month = month.name[MonthNum])
# write_csv(monthlyDORange, "output_data/DORange_stats_monthlyByStation.csv")
cols_to_keep <- colnames(subset.df)
df.DORange <- subset.df %>%
left_join(monthlyDORange, by = c("FDT_STA_ID", "MonthNum")) %>%
select(all_of(cols_to_keep), Mean)
```
```{r `DORange fit regressions for each month-station`, warning = FALSE}
# fit a linear regression for DORange vs. year by month-station using the mblm function (median based linear model) as this is thought to be less sensitive to outliers.
#Usage
#mblm(formula, dataframe, repeated = TRUE)
#Arguments
#formula A formula of type y ~ x (only linear models are accepted)
#dataframe Optional dataframe
#repeated If set to true, model is computed using repeated medians. If false, a single median estimators are calculated
# remove NA values -- mblm() does not handle NA as lm() does
df.DORange <- df.DORange %>%
filter(!is.na(DORange))
# create list to store regression results
modelSummaries <- list()
for (station_id in unique(df.DORange$FDT_STA_ID)) {
for (month_num in 5:10) {
month_station <- df.DORange %>%
filter(FDT_STA_ID == station_id & MonthNum == month_num)
model <- mblm(DORange ~ Year, data = month_station)
mod.sum <- summary.mblm(model)
# store results
modelSummaries[[paste(station_id, month_num, sep = "_")]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year", "MAD"] ,
pvalue = mod.sum$coefficients["Year", 4],
intercept = mod.sum$coefficients[1,1]
)
}
}
## --------DORange, with 1975 as y intercept-------------
q <- df.DORange %>%
mutate(Year1975 = Year - 1975) %>%
filter(MonthNum == 8)
modelSummaries_DORange1975 <- list()
for (station_id in unique(q$FDT_STA_ID)) {
data = subset(q, FDT_STA_ID == station_id)
model <- mblm(DORange ~ Year1975, data = data)
mod.sum <- summary.mblm(model)
# store results
modelSummaries_DORange1975[[paste(station_id)]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year1975", "MAD"] ,
pvalue = mod.sum$coefficients["Year1975", 4],
intercept = mod.sum$coefficients[1,1]
)
}
# mblm does not return a standard error. Instead, summary.mblm can be used to extract the MAD or Median Absolute Deviation." It's a robust measure of variability that is less sensitive to outliers than the standard deviation, which is commonly used in traditional statistical analyses.
```
```{r `DORange add reg stats to summary df`}
# create station-month key
monthlyDORange <- monthlyDORange %>%
mutate( key = paste(FDT_STA_ID, MonthNum, sep="_"),
model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA)
for (i in 1:nrow(monthlyDORange)) {
key = monthlyDORange$key[i]
monthlyDORange$model_slope[i] <- modelSummaries[[key]]$slope
monthlyDORange$model_MAD[i] <- modelSummaries[[key]]$MAD
monthlyDORange$model_pval[i] <- modelSummaries[[key]]$pvalue
monthlyDORange$model_intercept[i] <- modelSummaries[[key]]$intercept
}
DORange_final <- monthlyDORange %>%
filter(!key %in% insufficient_Nobs)
#--------------------------------------------
# reg stats for August DORange non-normalized with 1975 as y intercept
monthly_DORange1975 <- monthlyDORange %>%
mutate( model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA) %>%
filter(MonthNum == 8)
for (i in 1:nrow(monthly_DORange1975)) {
key = monthly_DORange1975$FDT_STA_ID[i]
monthly_DORange1975$model_slope[i] <- modelSummaries_DORange1975[[key]]$slope
monthly_DORange1975$model_MAD[i] <- modelSummaries_DORange1975[[key]]$MAD
monthly_DORange1975$model_pval[i] <- modelSummaries_DORange1975[[key]]$pvalue
monthly_DORange1975$model_intercept[i] <- modelSummaries_DORange1975[[key]]$intercept
}
DORange1975_final <- monthly_DORange1975 %>%
filter(!key %in% insufficient_Nobs)
#------------------------------------------------
write_csv(DORange_final, "output_data/DORange_mblmModelStatistics.csv")
# do any month-stations return a 0 slope with sig pval? In this case, no
wonky_results <- DORange_final %>%
filter(model_slope == 0 & model_pval <= 0.05)
paste(nrow(wonky_results), "station-months returned a slope of 0 with a significant p-value in DORange trend analysis.", sep=" ")
```
## Max Dissolved Oxygen
```{r `derive DOMax by month`, message = FALSE }
# This does not require filtering; surface only measurements are fine (?)
# Subset data more inclusively than in above calcs
DOMax.df <- allData.df %>%
mutate(MonthNum = lubridate::month(Date),
Year = lubridate::year(Date)) %>%
filter(FDT_STA_ID %in% station_IDS) %>%
filter(!FDT_STA_ID %in% c("6APNR008.15", "6ACNR000.00")) %>%
filter(MonthNum %in% 5:10)
countPerGroup_domax <- DOMax.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarise(Nobs = n()) %>%
mutate(key = paste(FDT_STA_ID, MonthNum, sep="_"))
insufficient_Nobs_domax <- countPerGroup_domax %>%
filter(Nobs < 10)
insufficient_Nobs_domax <- insufficient_Nobs_domax$key
#--------------------------
monthlyDOMax <- DOMax.df %>%
group_by(FDT_STA_ID, MonthNum) %>%
summarize(Mean = mean(DOMax, na.rm = TRUE),
Min = min(DOMax, na.rm = TRUE),
Max = max(DOMax, na.rm = TRUE),
Nobs = n(),
.groups = 'drop') %>%
mutate(Month = month.name[MonthNum])
# write_csv(monthlyDOMin, "output_data/DOMin_stats_monthlyByStation.csv")
cols_to_keep <- colnames(DOMax.df)
df.DOMax <- DOMax.df %>%
left_join(monthlyDOMax, by = c("FDT_STA_ID", "MonthNum")) %>%
select(all_of(cols_to_keep), Mean)
```
```{r `DOMax fit regressions for each month-station_DOMax`, warning=FALSE}
# fit a linear regression for DOMean vs. year by month-station using the mblm function (median based linear model) as this is thought to be less sensitive to outliers.
#Usage
#mblm(formula, dataframe, repeated = TRUE)
#Arguments
#formula A formula of type y ~ x (only linear models are accepted)
#dataframe Optional dataframe
#repeated If set to true, model is computed using repeated medians. If false, a single median estimators are calculated
# remove NA values -- mblm() does not handle NA as lm() does
df.DOMax <- df.DOMax %>%
filter(!is.na(DOMax))
# create list to store regression results
modelSummaries <- list()
for (station_id in unique(df.DOMax$FDT_STA_ID)) {
for (month_num in 5:10) {
month_station <- df.DOMax %>%
filter(FDT_STA_ID == station_id & MonthNum == month_num)
model <- mblm(DOMax ~ Year, data = month_station)
mod.sum <- summary.mblm(model)
# store results
modelSummaries[[paste(station_id, month_num, sep = "_")]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year", "MAD"] ,
pvalue = mod.sum$coefficients["Year", 4],
intercept = mod.sum$coefficients[1,1]
)
}
}
## --------DOMax, with 1975 as y intercept-------------
q <- df.DOMax %>%
mutate(Year1975 = Year - 1975) %>%
filter(MonthNum == 8)
modelSummaries_DOMax1975 <- list()
for (station_id in unique(q$FDT_STA_ID)) {
data = subset(q, FDT_STA_ID == station_id)
model <- mblm(DOMax ~ Year1975, data = data)
mod.sum <- summary.mblm(model)
# store results
modelSummaries_DOMax1975[[paste(station_id)]] <- list(
slope = mod.sum$coefficients[2,1],
MAD = mod.sum$coefficients["Year1975", "MAD"] ,
pvalue = mod.sum$coefficients["Year1975", 4],
intercept = mod.sum$coefficients[1,1]
)
}
# mblm does not return a standard error. Instead, summary.mblm can be used to extract the MAD or Median Absolute Deviation." It's a robust measure of variability that is less sensitive to outliers than the standard deviation, which is commonly used in traditional statistical analyses.
```
```{r `DOMax add reg stats to summary df_DOMax`}
# create station-month key
monthlyDOMax <- monthlyDOMax %>%
mutate( key = paste(FDT_STA_ID, MonthNum, sep="_"),
model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA)
for (i in 1:nrow(monthlyDOMax)) {
key = monthlyDOMax$key[i]
monthlyDOMax$model_slope[i] <- modelSummaries[[key]]$slope
monthlyDOMax$model_MAD[i] <- modelSummaries[[key]]$MAD
monthlyDOMax$model_pval[i] <- modelSummaries[[key]]$pvalue
monthlyDOMax$model_intercept[i] <- modelSummaries[[key]]$intercept
}
DOMax_final <- monthlyDOMax %>%
filter(!key %in% insufficient_Nobs)
#--------------------------------------------
# reg stats for August DOMax non-normalized with 1975 as y intercept
monthly_DOMax1975 <- monthlyDOMax %>%
mutate( model_slope = NA,
model_MAD = NA,
model_pval = NA,
model_intercept = NA) %>%
filter(MonthNum == 8)
for (i in 1:nrow(monthly_DOMax1975)) {
key = monthly_DOMax1975$FDT_STA_ID[i]
monthly_DOMax1975$model_slope[i] <- modelSummaries_DOMax1975[[key]]$slope
monthly_DOMax1975$model_MAD[i] <- modelSummaries_DOMax1975[[key]]$MAD
monthly_DOMax1975$model_pval[i] <- modelSummaries_DOMax1975[[key]]$pvalue
monthly_DOMax1975$model_intercept[i] <- modelSummaries_DOMax1975[[key]]$intercept
}
DOMax1975_final <- monthly_DOMax1975 %>%
filter(!key %in% insufficient_Nobs)
#------------------------------------------------
write_csv(DOMax_final, "output_data/DOMax_mblmModelStatistics.csv")
# do any month-stations return a 0 slope with sig pval? In this case, no
wonky_results <- DOMax_final %>%
filter(model_slope == 0 & model_pval <= 0.05)
paste(nrow(wonky_results), "station-months returned a slope of 0 with a significant p-value in DOMax trend analysis.", sep=" ")
```
### Single df with all 1975 y intercept model results
```{r}
a <- DOMin1975_final %>%
mutate(variable = "DOMin")
b <- DOMean1975_final %>%
mutate(variable = "DOMean")
c <- DORange1975_final %>%
mutate(variable = "DORange")
d <- DOMax1975_final %>%
mutate(variable = "DOMax")
e <- rbind(a, b, c, d)
readr::write_csv(e, "output_data/1975_y_intercept_DOVars_model_results.csv")
```
## Data viz
"a box-whisker plot showing the distribution of values by month across all stations."
```{r `custom func`}
# custom function to prepare plotting data for each variable
makePlotData <- function(df) {
# derive mean warming and incorporate back into df for plotting
df.allMonths <- df %>%
group_by(FDT_STA_ID) %>%
summarize(mean_slope = mean(model_slope, na.rm = TRUE),
.groups = "drop") %>%
mutate(Month = "All Months",
trend= "N/A")
df.plot <- bind_rows(df, df.allMonths)
# populate model slope column with mean slope where Month == "All Months"
df.plot <- df.plot %>%
mutate(model_slope = if_else(Month == "All Months", mean_slope, model_slope))
# set month as factor
df.plot <- df.plot %>%
mutate(Month = factor(Month, levels = c("January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December", "All Months")),
trend = ifelse(is.na(df.plot$model_pval), "N/A",
ifelse(df.plot$model_pval <= 0.05, "significant", "not significant")))
df.plot$trend <- factor(df.plot$trend, levels = c("significant", "not significant", "N/A"))
return(df.plot)
}
```
### DOMin
```{r}
DOMin_plot.df <- makePlotData(DOMin_final)
ggplot(DOMin_plot.df, aes(x = Month, y = model_slope, fill = Month)) +
geom_boxplot(alpha = .85) +
labs(title = "Variation in Warming Rates by Month (DOMin)",
x = "Month",
y = "T Trend (C/y)",
fill = "Month") +
theme_minimal() +
theme(axis.title.x = element_text(margin = margin(t = 10)),
legend.position = "none")
ggsave("output_data/DOMin_variationByMonth.jpg")
```
### DOMean
```{r}
DOMean_plot.df <- makePlotData(DOMean_final)
ggplot(DOMean_plot.df, aes(x = Month, y = model_slope, fill = Month)) +
geom_boxplot(alpha = .85) +
labs(title = "Variation in Warming Rates by Month (DOMean)",
x = "Month",
y = "T Trend (C/y)",
fill = "Month") +
theme_minimal() +
theme(axis.title.x = element_text(margin = margin(t = 10)),
legend.position = "none")
ggsave("output_data/DOMean_variationByMonth.jpg")
```
### TRange
```{r}
DORange_plot.df <- makePlotData(DORange_final)
ggplot(DORange_plot.df, aes(x = Month, y = model_slope, fill = Month)) +
geom_boxplot(alpha = .85) +
labs(title = "Variation in Warming Rates by Month (DORange)",
x = "Month",
y = "T Trend (C/y)",
fill = "Month") +
theme_minimal() +
theme(axis.title.x = element_text(margin = margin(t = 10)),
legend.position = "none")
ggsave("output_data/DORange_variationByMonth.jpg")
```