-
Notifications
You must be signed in to change notification settings - Fork 18
/
ResultFlagsIndependent.R
1378 lines (1252 loc) · 63.3 KB
/
ResultFlagsIndependent.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
#' Check for Invalid Analytical Methods
#'
#' Function checks the validity of each characteristic-analytical method
#' combination in the dataframe. When clean = TRUE, rows with invalid
#' characteristic-analytical method combinations are removed. Default is
#' clean = TRUE. When flaggedonly = TRUE, dataframe is filtered to show only
#' invalid characteristic-analytical method combinations. Default is
#' flaggedonly = FALSE.
#'
#' The “Not Reviewed” value within "TADA.ResultAboveUpperThreshold.Flag" means
#' that the EPA WQX team has not yet reviewed the combinations
#' (see https://cdx.epa.gov/wqx/download/DomainValues/QAQCCharacteristicValidation.CSV).
#' The WQX team plans to review and update these new combinations quarterly.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument; removes "Invalid" characteristic-analytical
#' method combinations from the dataframe when clean = TRUE. Default is
#' clean = TRUE.
#' @param flaggedonly Boolean argument; filters dataframe to show only "Invalid"
#' characteristic-analytical method combinations when flaggedonly = TRUE. Default
#' is flaggedonly = FALSE.
#'
#' @return This function adds the TADA.AnalyticalMethod.Flag to a TADA dataframe. This column
#' flags invalid CharacteristicName, ResultAnalyticalMethod/MethodIdentifier,
#' and ResultAnalyticalMethod/MethodIdentifierContext combinations in your dataframe
#' as either "Not Reviewed", "Invalid", or "Valid". When clean = FALSE and
#' flaggedonly = TRUE, the dataframe is filtered to show only "Invalid"
#' characteristic-analytical method combinations; the column TADA.AnalyticalMethod.Flag
#' is still appended. When clean = TRUE and flaggedonly = FALSE, "Invalid" rows
#' are removed from the dataframe and no column will be appended.
#'
#' @export
#'
#' @examples
#' # Load example dataset
#' data(Data_NCTCShepherdstown_HUC12)
#'
#' # Remove invalid characteristic-analytical method combinations from dataframe:
#' InvalidMethod_clean <- TADA_FlagMethod(Data_NCTCShepherdstown_HUC12, clean = TRUE)
#'
#' # Flag, but do not remove, invalid characteristic-analytical method combinations
#' # in new column titled "TADA.AnalyticalMethod.Flag":
#' InvalidMethod_flags <- TADA_FlagMethod(Data_NCTCShepherdstown_HUC12, clean = FALSE)
#'
#' # Show only invalid characteristic-analytical method combinations:
#' InvalidMethod_flaggedonly <- TADA_FlagMethod(Data_NCTCShepherdstown_HUC12, clean = FALSE, flaggedonly = TRUE)
#'
TADA_FlagMethod <- function(.data, clean = TRUE, flaggedonly = FALSE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check flaggedonly is boolean
TADA_CheckType(flaggedonly, "logical")
# check .data has required columns
required_cols <- c(
"TADA.CharacteristicName", "ResultAnalyticalMethod.MethodIdentifier",
"ResultAnalyticalMethod.MethodIdentifierContext"
)
TADA_CheckColumns(.data, required_cols)
# check that clean and flaggedonly are not both TRUE
if (clean == TRUE & flaggedonly == TRUE) {
stop("Function not executed because clean and flaggedonly cannot both be TRUE")
}
# execute function after checks are passed - removes flag column in case reference table has changed.
# delete existing flag column
if (("TADA.AnalyticalMethod.Flag" %in% colnames(.data)) == TRUE) {
.data <- dplyr::select(.data, -TADA.AnalyticalMethod.Flag)
}
# read in WQX val reference table and filter
meth.ref <- utils::read.csv(system.file("extdata", "WQXcharValRef.csv", package = "EPATADA")) %>%
dplyr::filter(Type == "CharacteristicMethod")
# join "TADA.WQXVal.Flag" column to .data by CharacteristicName, Source (Media), and Value (unit)
check.data <- merge(.data, meth.ref[, c("Characteristic", "Source", "Value", "TADA.WQXVal.Flag")],
by.x = c(
"TADA.CharacteristicName", "ResultAnalyticalMethod.MethodIdentifier",
"ResultAnalyticalMethod.MethodIdentifierContext"
),
by.y = c("Characteristic", "Value", "Source"), all.x = TRUE
)
# rename TADA.WQXVal.Flag column to WQX.AnalyticalMethodValidity
check.data <- check.data %>%
dplyr::rename(TADA.AnalyticalMethod.Flag = TADA.WQXVal.Flag) %>%
dplyr::distinct()
# rename NA values to NonStandardized in WQX.AnalyticalMethodValidity column
check.data["TADA.AnalyticalMethod.Flag"][is.na(check.data["TADA.AnalyticalMethod.Flag"])] <- "Not Reviewed"
if (flaggedonly == FALSE) {
# if all rows are "Valid" or NA "Not Reviewed", return input unchanged
## note: Cristina edited this on 9/19/22 to keep Not Reviewed/NA data when clean = TRUE. Now only Invalid data is removed.
if (any("Invalid" %in%
unique(check.data$TADA.AnalyticalMethod.Flag)) == FALSE) {
print("No invalid method/characteristic combinations in your dataframe. Returning the input dataframe with TADA.AnalyticalMethod.Flag column for tracking.")
check.data <- TADA_OrderCols(check.data)
return(check.data)
}
# flagged output, all data
if (clean == FALSE) {
check.data <- TADA_OrderCols(check.data)
return(check.data)
}
# clean output
if (clean == TRUE) {
# filter out invalid characteristic-unit-method combinations
clean.data <- dplyr::filter(check.data, TADA.AnalyticalMethod.Flag != "Invalid")
# remove WQX.AnalyticalMethodValidity column
# clean.data <- dplyr::select(clean.data, -TADA.AnalyticalMethod.Flag)
clean.data <- TADA_OrderCols(clean.data)
return(clean.data)
}
}
# flagged output, errors only
if (clean == FALSE & flaggedonly == TRUE) {
# filter to show only invalid characteristic-unit-method combinations
invalid.data <- dplyr::filter(check.data, TADA.AnalyticalMethod.Flag == "Invalid")
if (nrow(invalid.data) == 0) {
# invalid.data <- dplyr::select(invalid.data, -TADA.AnalyticalMethod.Flag)
print("This dataframe is empty because we did not find any invalid method/characteristic combinations in your dataframe")
}
invalid.data <- TADA_OrderCols(invalid.data)
return(invalid.data)
}
}
#' Flag Continuous Data
#'
#' Continuous data may (or may not) be suitable for integration with discrete
#' water quality data for analyses. Therefore, this function uses metadata
#' submitted by data providers to flag rows with continuous data.
#'
#' Continuous data is often aggregated to a daily avg, max, and min value,
#' or another statistic of interest to the data submitter. Alternatively, some
#' organizations aggregate their high frequency data (15 min or 1 hour data)
#' to 2 or 4 hour interval averages. In all of these scenarios, the data provider
#' may have also included the raw data (full continuous time series) as a text file
#' attachment at the activity level.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument: When clean = FALSE (default), a column titled
#' "TADA.ContinuousData.Flag" is added to the dataframe to indicate if
#' each row includes "Continuous" or "Discrete" data. When clean = TRUE, rows
#' with "Continuous" data are removed from the dataframe and no column is appended.
#' @param flaggedonly Boolean argument: When flaggedonly = FALSE (default), all
#' results are included in the output. When flaggedonly = TRUE, the dataframe
#' will be filtered to include only the rows flagged as "Continuous" results.
#' @param time_difference Numeric argument defining the maximum time difference
#' in hours between measurements of the same TADA.ComparableDataIdentifier taken at the same
#' latitude, longitude, and depth. This is used to search for
#' continuous time series data (i.e., if there are multiple measurements within the selected
#' time_difference, then the row will be flagged as continuous). The default time window is 4 hours.
#' The time_difference can be adjusted by the user.
#' @return The default is clean = FALSE and flaggedonly = FALSE.
#' When clean = FALSE and flaggedonly = FALSE (default), a new column,
#' "TADA.ContinuousData.Flag", is appended to the input data set which
#' flags each row as "Continuous" or "Discrete".
#' When clean = FALSE and flaggedonly = TRUE, the dataframe is filtered to show
#' only the flagged continuous data and the flag column is still appended.
#' When clean = TRUE and flaggedonly = FALSE, continuous data is
#' removed from the dataframe and no column is appended.
#'
#' @export
#'
#' @examples
#' \dontrun{
#' all_data <- TADA_DataRetrieval(project = c("Continuous LC1", "MA_Continuous", "Anchorage Bacteria 20-21"))
#'
#' # Flag continuous data in new column titled "TADA.ContinuousData.Flag"
#' all_data_flags <- TADA_FlagContinuousData(all_data, clean = FALSE)
#'
#' # Show only rows flagged as continuous data (note that all results are flagged in the example)
#' all_data_flaggedonly <- TADA_FlagContinuousData(all_data, clean = FALSE, flaggedonly = TRUE)
#'
#' # Remove continuous data in dataframe (note that this dataframe will have 0 results because all are flagged in the example)
#' all_data_clean <- TADA_FlagContinuousData(all_data, clean = TRUE)
#'
#' data(Data_Nutrients_UT)
#'
#' # Flag continuous data in new column titled "TADA.ContinuousData.Flag"
#' Data_Nutrients_UT_flags <- TADA_FlagContinuousData(Data_Nutrients_UT, clean = FALSE)
#' unique(Data_Nutrients_UT_flags$TADA.ContinuousData.Flag)
#'
#' # Show only rows flagged as continuous data
#' Data_Nutrients_UT_flaggedonly <- TADA_FlagContinuousData(Data_Nutrients_UT, clean = FALSE, flaggedonly = TRUE)
#'
#' # Remove continuous data in dataframe
#' Data_Nutrients_UT_clean <- TADA_FlagContinuousData(Data_Nutrients_UT, clean = TRUE)
#' unique(Data_Nutrients_UT_clean$TADA.ContinuousData.Flag)
#' }
#'
TADA_FlagContinuousData <- function(.data, clean = FALSE, flaggedonly = FALSE, time_difference = 4) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check flaggedonly is boolean
TADA_CheckType(flaggedonly, "logical")
# check .data has required columns
TADA_CheckColumns(.data, c(
"ActivityTypeCode",
"SampleCollectionEquipmentName",
"ResultDetectionConditionText",
"ResultTimeBasisText",
"StatisticalBaseCode",
"ResultValueTypeName",
"ResultIdentifier"
))
# check that clean and flaggedonly are not both TRUE
if (clean == TRUE & flaggedonly == TRUE) {
stop("Function not executed because clean and flaggedonly cannot both be TRUE")
}
# run autoclean if it has not already been run
if ("TADA.ActivityMediaName" %in% colnames(.data)) {
.data <- .data
} else {
# run autoclean
.data <- TADA_AutoClean(.data)
}
# run TADA_IDCensoredData if it has not already been run
if ("TADA.CensoredData.Flag" %in% colnames(.data)) {
.data <- .data
} else {
# run TADA_IDCensoredData
.data <- TADA_IDCensoredData(.data)
}
# execute function after checks are passed: flag continuous data and make cont.data data frame
# set default flag to "Discrete"
.data$TADA.ContinuousData.Flag <- "Discrete"
# once new 3.0 profiles come out, check for zip files in ActivityFileURL and flag data that populates the DataLoggerLine
cont.data <- .data %>% dplyr::filter((ActivityTypeCode == "Field Msr/Obs-Continuous Time Series" | # ID cont data with new activity type code from 2023
grepl("Continuous", ProjectIdentifier) | # ID cont data by looking for string in project ID
grepl("CONTINUOUS", ProjectIdentifier) | # ID cont data by looking for string in project ID
(ActivityTypeCode == "Sample-Integrated Time Series" & SampleCollectionEquipmentName == "Probe/Sensor") |
(ActivityTypeCode == "Field Msr/Obs-Portable Data Logger" & !is.na(ResultTimeBasisText)) |
(ActivityTypeCode == "Field Msr/Obs-Portable Data Logger" & !is.na(StatisticalBaseCode)) |
(ActivityTypeCode == "Field Msr/Obs-Portable Data Logger" & ResultValueTypeName == "Calculated") |
(ActivityTypeCode == "Field Msr/Obs-Portable Data Logger" & ResultValueTypeName == "Estimated") |
# SampleCollectionEquipmentName == "Probe/Sensor" & !is.na(ActivityFileURL) |
# (SampleCollectionEquipmentName == "Probe/Sensor" & !is.na(DataLoggerLine)) |
(SampleCollectionEquipmentName == "Probe/Sensor" & !is.na(ResultTimeBasisText)) |
(SampleCollectionEquipmentName == "Probe/Sensor" & !is.na(StatisticalBaseCode)) |
(SampleCollectionEquipmentName == "Probe/Sensor" & ResultValueTypeName == "Calculated") |
(SampleCollectionEquipmentName == "Probe/Sensor" & ResultValueTypeName == "Estimated"))) %>%
dplyr::mutate(TADA.ContinuousData.Flag = "Continuous")
# everything not YET in cont dataframe
noncont.data <- subset(.data, !.data$ResultIdentifier %in% cont.data$ResultIdentifier)
# if time field is not NA, find time difference between results
if (length(noncont.data) >= 1) {
info_match <- noncont.data %>%
dplyr::group_by(
TADA.LatitudeMeasure, TADA.LongitudeMeasure,
OrganizationIdentifier, TADA.ComparableDataIdentifier,
TADA.ActivityDepthHeightMeasure.MeasureValue,
TADA.ResultDepthHeightMeasure.MeasureValue,
TADA.ActivityBottomDepthHeightMeasure.MeasureValue,
TADA.ActivityTopDepthHeightMeasure.MeasureValue,
ActivityRelativeDepthName
) %>%
dplyr::mutate(n_records = length(TADA.ResultMeasureValue)) %>%
dplyr::mutate(group_id = dplyr::cur_group_id()) %>%
dplyr::filter(n_records > 1) %>%
dplyr::ungroup() %>%
dplyr::group_by(group_id) %>%
dplyr::arrange(ActivityStartDateTime, .by_group = TRUE) %>%
dplyr::mutate(
time_diff_lag = abs(difftime(ActivityStartDateTime, dplyr::lag(ActivityStartDateTime), units = "hours")),
time_diff_lead = abs(difftime(ActivityStartDateTime, dplyr::lead(ActivityStartDateTime), units = "hours"))
) %>%
dplyr::ungroup()
# find results where the time differences is <= time_difference (default is 4 hours)
within_window <- info_match %>%
dplyr::filter(time_diff_lead <= time_difference |
time_diff_lag <= time_difference)
rm(info_match)
# if matches are identified change flag to continuous
noncont.data <- noncont.data %>%
dplyr::mutate(TADA.ContinuousData.Flag = ifelse(ResultIdentifier %in% within_window$ResultIdentifier,
"Continuous", TADA.ContinuousData.Flag
))
rm(within_window)
}
flag.data <- cont.data %>%
dplyr::full_join(noncont.data, by = c(names(cont.data)))
# flagged output, all data
if (clean == FALSE & flaggedonly == FALSE) {
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
# clean output
if (clean == TRUE & flaggedonly == FALSE) {
# filter out invalid characteristic-unit-media combinations
clean.data <- flag.data %>%
dplyr::filter(!(TADA.ContinuousData.Flag %in% "Continuous")) %>%
dplyr::select(-TADA.ContinuousData.Flag) %>%
TADA_OrderCols()
return(clean.data)
}
# flagged output, only aggregated continuous data
if (clean == FALSE & flaggedonly == TRUE) {
# filter to show only invalid characteristic-unit-media combinations
onlycont.data <- flag.data %>%
dplyr::filter(TADA.ContinuousData.Flag == "Continuous") %>%
TADA_OrderCols()
return(onlycont.data)
}
# if no aggregated continuous data is in the data set
if (nrow(flag.data[flag.data$TADA.ContinuousData.Flag == "Continuous", ]) == 0) {
if (flaggedonly == FALSE) {
print("No evidence of aggregated continuous data in your dataframe. Returning the input dataframe with TADA.ContinuousData.Flag column for tracking.")
.data <- TADA_OrderCols(.data)
return(.data)
}
if (flaggedonly == TRUE) {
print("This dataframe is empty because we did not find any aggregated continuous data in your dataframe")
all.cont.data <- flag.data %>%
dplyr::filter(TADA.ContinuousData.Flag == "Continuous")
return(all.cont.data)
}
}
}
#' Check Result Value Against WQX Upper Threshold
#'
#' EPA's Water Quality Exchange (WQX) has generated maximum and minimum thresholds
#' for each parameter and unit combination from millions of water quality data
#' points around the country. This function leverages the WQX QAQC Validation Table
#' to flag any data that is above the upper threshold of result values submitted
#' to WQX for a given characteristic.
#'
#' When clean = FALSE and flaggedonly = FALSE, a column which flags data above
#' the upper WQX threshold is appended to the dataframe. When clean = FALSE and
#' flaggedonly = TRUE, the dataframe is filtered to show only data found above
#' the WQX threshold. When clean = TRUE and flaggedonly = FALSE, rows with values
#' that are above the upper WQX threshold are removed from the dataframe and no
#' column is appended. When clean = TRUE and and flaggedonly = TRUE, the function
#' is not executed and an error message is returned. Defaults are clean = FALSE
#' and flaggedonly = FALSE.
#'
#' This function will add the column "TADA.ResultAboveUpperThreshold.Flag" which
#' will be populated with the values: "Pass", "Suspect", "Not Reviewed", or
#' "NA - Not Available". The “Not Reviewed” value means that the EPA WQX team
#' has not yet reviewed the range yet for the characteristic and unit combination combination
#' in that row (see https://cdx.epa.gov/wqx/download/DomainValues/QAQCCharacteristicValidation.CSV).
#' The WQX team plans to review and update these new combinations quarterly. The
#' "NA - Not Available" flag means that the characteristic, media, and/or unit combination
#' for that row is not fully populated (is NA or does not match the WQX data standard)
#' or the result value is NA.
#'
#' If this function is run more than once on the same dataframe,
#' the flag column will be deleted and regenerated.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument; removes data that is above the upper WQX
#' threshold from the dataframe when clean = TRUE. Default is clean = FALSE.
#' @param flaggedonly Boolean argument; filters dataframe to show only the data
#' flagged as above the upper WQX threshold. Default is flaggedonly = FALSE.
#' @return The input TADA dataset with the added "TADA.ResultAboveUpperThreshold.Flag"
#' column which is populated with the values: "Pass", "Suspect", "Not Reviewed", or
#' "NA - Not Available". Defaults are clean = FALSE and flaggedonly = FALSE.
#' When clean = FALSE and flaggedonly = TRUE, the dataframe
#' is filtered to show only data found above the WQX threshold. When clean = TRUE
#' and flaggedonly = FALSE, rows with values that are above the upper WQX threshold
#' are removed from the dataframe. When clean = TRUE and and flaggedonly = TRUE,
#' the function is not executed and an error message is returned.
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' data(Data_Nutrients_UT)
#'
#' # Remove data that is above the upper WQX threshold from dataframe:
#' WQXUpperThreshold_clean <- TADA_FlagAboveThreshold(Data_Nutrients_UT, clean = TRUE)
#'
#' # Flag, but do not remove, data that is above the upper WQX threshold in
#' # new column titled "TADA.ResultValueAboveUpperThreshold.Flag":
#' WQXUpperThreshold_flags <- TADA_FlagAboveThreshold(Data_Nutrients_UT, clean = FALSE)
#'
#' # Show only data flagged as above the upper WQX threshold:
#' WQXUpperThreshold_flagsonly <- TADA_FlagAboveThreshold(Data_Nutrients_UT, clean = FALSE, flaggedonly = TRUE)
#'
TADA_FlagAboveThreshold <- function(.data, clean = FALSE, flaggedonly = FALSE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check flaggedonly is boolean
TADA_CheckType(flaggedonly, "logical")
# check .data has required columns
required_cols <- c(
"TADA.CharacteristicName", "TADA.ActivityMediaName", "TADA.ResultMeasureValue",
"TADA.ResultMeasure.MeasureUnitCode"
)
TADA_CheckColumns(.data, required_cols)
# check that clean and flaggedonly are not both TRUE
if (clean == TRUE & flaggedonly == TRUE) {
stop("Function not executed because clean and flaggedonly cannot both be TRUE")
}
# check ResultMeasureValue column is of class numeric
if (!is.numeric(.data$TADA.ResultMeasureValue)) {
stop("The ResultMeasureValue column must be of class 'numeric'.")
}
# execute function after checks are passed
# delete existing flag column - removes flag column in case reference table has changed.
if (("TADA.ResultValueAboveUpperThreshold.Flag" %in% colnames(.data)) == TRUE) {
.data <- dplyr::select(.data, -TADA.ResultValueAboveUpperThreshold.Flag)
}
# get WQXcharVal.ref and filter to include only CharacteristicUnit.
# Note that status is not applicable to ranges.
# Instead, we generate a validation flag later in this function
unit.ref <- utils::read.csv(system.file("extdata", "WQXcharValRef.csv", package = "EPATADA")) %>%
dplyr::filter(Type == "CharacteristicUnit")
# update ref table names to prepare for left join with df
names(unit.ref)[names(unit.ref) == "Characteristic"] <- "TADA.CharacteristicName"
names(unit.ref)[names(unit.ref) == "Source"] <- "TADA.ActivityMediaName"
names(unit.ref)[names(unit.ref) == "Value.Unit"] <- "TADA.ResultMeasure.MeasureUnitCode"
# remove extraneous columns from unit.ref
unit.ref <- dplyr::select(unit.ref, c(
-Type, -Unique.Identifier, -Domain,
-Status, -TADA.WQXVal.Flag,
-Note.Recommendation,
-Conversion.Factor,
-Conversion.Coefficient,
-Last.Change.Date,
-Value,
-Minimum
))
unit.ref <- unique(unit.ref)
check.data <- dplyr::left_join(.data,
unit.ref,
by = c(
"TADA.CharacteristicName",
"TADA.ActivityMediaName",
"TADA.ResultMeasure.MeasureUnitCode"
),
multiple = "any", # this should be "all" but the validation table has issues
relationship = "many-to-many" # this should be "one-to-one" but the validation table has issues
)
# Create flag column, flag rows where ResultMeasureValue > Maximum
flag.data <- check.data %>%
# create flag column
dplyr::mutate(TADA.ResultValueAboveUpperThreshold.Flag = dplyr::case_when(
TADA.ResultMeasureValue >= Maximum ~ as.character("Suspect"),
TADA.ResultMeasureValue < Maximum ~ as.character("Pass"),
is.na(Maximum) ~ as.character("Not Reviewed"), # in QAQC table, but not yet reviewed
TRUE ~ as.character("NA - Not Available") # this occurs when the char/unit/media combo is not in the WQX QAQC table at all. USGS data may not be in QAQC table because it does not adhere to the WQX domain tables.
))
# remove Maximum column
flag.data <- flag.data %>%
dplyr::select(-"Maximum")
# if no data above WQX threshold is found
if (any("Suspect" %in%
unique(flag.data$TADA.ResultValueAboveUpperThreshold.Flag)) == FALSE) {
if (flaggedonly == FALSE) {
print("No data above the WQX Upper Threshold was found in your dataframe. Returning the input dataframe with TADA.ResultAboveUpperThreshold.Flag column for tracking.")
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
if (flaggedonly == TRUE) {
print("This dataframe is empty because no data above the WQX Upper Threshold was found in your dataframe")
emptyflag.data <- dplyr::filter(flag.data, TADA.ResultValueAboveUpperThreshold.Flag %in% "Suspect")
emptyflag.data <- TADA_OrderCols(emptyflag.data)
return(emptyflag.data)
}
}
# flagged, all data
if (clean == FALSE & flaggedonly == FALSE) {
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
# clean data
if (clean == TRUE & flaggedonly == FALSE) {
# filter out rows where TADA.ResultValueAboveUpperThreshold.Flag = Suspect; remove TADA.ResultValueAboveUpperThreshold.Flag column
clean.data <- flag.data %>%
dplyr::filter(!(TADA.ResultValueAboveUpperThreshold.Flag %in% "Suspect")) # %>%
# dplyr::select(-TADA.ResultValueAboveUpperThreshold.Flag)
clean.data <- TADA_OrderCols(clean.data)
return(clean.data)
}
# flagged, errors only
if (clean == FALSE & flaggedonly == TRUE) {
# filter to show only rows above WQX upper threshold
flagsonly.data <- flag.data %>%
dplyr::filter(TADA.ResultValueAboveUpperThreshold.Flag %in% "Suspect")
flagsonly.data <- TADA_OrderCols(flagsonly.data)
return(flagsonly.data)
}
}
#' Check Result Value Against WQX Lower Threshold
#'
#' EPA's Water Quality Exchange (WQX) has generated maximum and minimum thresholds
#' for each parameter and unit combination from millions of water quality data
#' points around the country. This function leverages the WQX QAQC Validation Table
#' to flag any data that is below the lower threshold of result values submitted
#' to WQX for a given characteristic.
#'
#' When clean = FALSE and flaggedonly = FALSE, a column which flags data below
#' the lower WQX threshold is appended to the dataframe. When clean = FALSE and
#' flaggedonly = TRUE, the dataframe is filtered to show only data found below
#' the WQX threshold. When clean = TRUE and flaggedonly = FALSE, rows with values
#' that are below the upper WQX threshold are removed from the dataframe and no
#' column is appended. When clean = TRUE and and flaggedonly = TRUE, the function
#' is not executed and an error message is returned. Defaults are clean = FALSE
#' and flaggedonly = FALSE.
#'
#' This function will add the column "TADA.ResultValueBelowLowerThreshold.Flag" which
#' will be populated with the values: "Pass", "Suspect", "Not Reviewed", or
#' "NA - Not Available". The “Not Reviewed” value means that the EPA WQX team
#' has not yet reviewed the range yet for the characteristic and unit combination combination
#' in that row (see https://cdx.epa.gov/wqx/download/DomainValues/QAQCCharacteristicValidation.CSV).
#' The WQX team plans to review and update these new combinations quarterly. The
#' "NA - Not Available" flag means that the characteristic, media, and/or unit combination
#' for that row is not fully populated (is NA or does not match the WQX data standard)
#' or the result value is NA.
#'
#' If this function is run more than once on the same dataframe,
#' the flag column will be deleted and regenerated.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument; removes data that is below the lower WQX
#' threshold from the dataframe when clean = TRUE. Default is clean = FALSE.
#' @param flaggedonly Boolean argument; filters dataframe to show only the data
#' flagged as below the lower WQX threshold. Default is flaggedonly = FALSE.
#' @return The input TADA dataset with the added "TADA.ResultValueBelowLowerThreshold.Flag"
#' column which is populated with the values: "Pass", "Suspect", "Not Reviewed", or
#' "NA - Not Available". Defaults are clean = FALSE and flaggedonly = FALSE.
#' When clean = FALSE and flaggedonly = TRUE, the dataframe
#' is filtered to show only data found below the WQX threshold. When clean = TRUE
#' and flaggedonly = FALSE, rows with values that are below the lower WQX threshold
#' are removed from the dataframe. When clean = TRUE and and flaggedonly = TRUE,
#' the function is not executed and an error message is returned.
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' data(Data_Nutrients_UT)
#'
#' # Remove data that is below the lower WQX threshold from the dataframe:
#' WQXLowerThreshold_clean <- TADA_FlagBelowThreshold(Data_Nutrients_UT, clean = TRUE)
#'
#' # Flag, but do not remove, data that is below the lower WQX threshold in
#' # new column titled "TADA.ResultValueBelowLowerThreshold.Flag":
#' WQXLowerThreshold_flags <- TADA_FlagBelowThreshold(Data_Nutrients_UT, clean = FALSE)
#'
#' # Show only data that is below the lower WQX threshold:
#' WQXLowerThreshold_flagsonly <- TADA_FlagBelowThreshold(Data_Nutrients_UT, clean = FALSE, flaggedonly = TRUE)
#'
TADA_FlagBelowThreshold <- function(.data, clean = FALSE, flaggedonly = FALSE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check flaggedonly is boolean
TADA_CheckType(flaggedonly, "logical")
# check .data has required columns
required_cols <- c(
"TADA.CharacteristicName", "TADA.ActivityMediaName", "TADA.ResultMeasureValue",
"TADA.ResultMeasure.MeasureUnitCode"
)
TADA_CheckColumns(.data, required_cols)
# check that clean and flaggedonly are not both TRUE
if (clean == TRUE & flaggedonly == TRUE) {
stop("Function not executed because clean and flaggedonly cannot both be TRUE")
}
# check ResultMeasureValue column is of class numeric
if (!is.numeric(.data$TADA.ResultMeasureValue)) {
stop("The ResultMeasureValue column must be of class 'numeric'.")
}
# execute function after checks are passed - removes flag column in case reference table has changed.
# delete existing flag column
if (("TADA.ResultValueBelowLowerThreshold.Flag" %in% colnames(.data)) == TRUE) {
.data <- dplyr::select(.data, -TADA.ResultValueBelowLowerThreshold.Flag)
}
# get WQXcharVal.ref and filter to include only CharacteristicUnit
# Note that status is not applicable to ranges.
# Instead, we generate a validation flag later in this function
unit.ref <- utils::read.csv(system.file("extdata", "WQXcharValRef.csv", package = "EPATADA")) %>%
dplyr::filter(Type == "CharacteristicUnit")
# update ref table names to prepare for left join with df
names(unit.ref)[names(unit.ref) == "Characteristic"] <- "TADA.CharacteristicName"
names(unit.ref)[names(unit.ref) == "Source"] <- "TADA.ActivityMediaName"
names(unit.ref)[names(unit.ref) == "Value.Unit"] <- "TADA.ResultMeasure.MeasureUnitCode"
# remove extraneous columns from unit.ref
unit.ref <- dplyr::select(unit.ref, c(
-Type, -Unique.Identifier, -Domain,
-Status, -TADA.WQXVal.Flag,
-Note.Recommendation,
-Conversion.Factor,
-Conversion.Coefficient,
-Last.Change.Date,
-Value,
-Maximum
))
unit.ref <- unique(unit.ref)
check.data <- dplyr::left_join(.data,
unit.ref,
by = c(
"TADA.CharacteristicName",
"TADA.ActivityMediaName",
"TADA.ResultMeasure.MeasureUnitCode"
),
multiple = "any", # this should be "all" but the validation table has issues
relationship = "many-to-many" # this should be "one-to-one" but the validation table has issues
)
# Create flag column, flag rows where TADA.ResultMeasureValue < Minimum
flag.data <- check.data %>%
# create flag column
dplyr::mutate(TADA.ResultValueBelowLowerThreshold.Flag = dplyr::case_when(
TADA.ResultMeasureValue < Minimum ~ as.character("Suspect"),
TADA.ResultMeasureValue >= Minimum ~ as.character("Pass"),
is.na(Minimum) ~ as.character("Not Reviewed"), # in QAQC table but not reviewed
TRUE ~ as.character("NA - Not Available") # this occurs when the char/unit/media combo is not in the WQX QAQC table at all. USGS data may not be in QAQC table because it does not adhere to the WQX domain tables.
))
# remove Min column
flag.data <- flag.data %>%
dplyr::select(-"Minimum")
# if no data below WQX lower threshold is found
if (any("Suspect" %in%
unique(flag.data$TADA.ResultValueBelowLowerThreshold.Flag)) == FALSE) {
if (flaggedonly == FALSE) {
print("No data below the WQX Lower Threshold were found in your dataframe. Returning the input dataframe with TADA.ResultValueBelowLowerThreshold.Flag column for tracking.")
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
if (flaggedonly == TRUE) {
print("This dataframe is empty because no data below the WQX Lower Threshold was found in your dataframe")
emptyflag.data <- dplyr::filter(flag.data, TADA.ResultValueBelowLowerThreshold.Flag %in% "Suspect")
emptyflag.data <- TADA_OrderCols(emptyflag.data)
return(emptyflag.data)
}
}
# flagged, all data
if (clean == FALSE & flaggedonly == FALSE) {
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
# clean data
if (clean == TRUE & flaggedonly == FALSE) {
# filter out rows where TADA.ResultValueBelowLowerThreshold.Flag = Suspect; remove TADA.ResultValueBelowLowerThreshold.Flag column
clean.data <- flag.data %>%
dplyr::filter(!(TADA.ResultValueBelowLowerThreshold.Flag %in% "Suspect"))
clean.data <- TADA_OrderCols(clean.data)
return(clean.data)
}
# only flagged data
if (clean == FALSE & flaggedonly == TRUE) {
# filter to show only rows where TADA.ResultValueBelowLowerThreshold.Flag = Suspect
flagsonly.data <- flag.data %>%
dplyr::filter(TADA.ResultValueBelowLowerThreshold.Flag %in% "Suspect")
flagsonly.data <- TADA_OrderCols(flagsonly.data)
return(flagsonly.data)
}
}
#' Check data for an approved QAPP
#'
#' Function checks data submitted under the column "QAPPApprovedIndicator".
#' Some organizations submit data for this field to indicate if the data
#' produced has an approved Quality Assurance Project Plan (QAPP) or not.
#' Y indicates yes, N indicates no. This function has three default inputs:
#' clean = TRUE, cleanNA = FALSE, and flaggedonly == FALSE. The default flags
#' rows of data where the QAPPApprovedIndicator equals "N". Users could
#' remove NA's in addition to N's using the inputs clean = TRUE, cleanNA = TRUE,
#' and flaggedonly = FALSE. If flaggedonly = TRUE, the function will filter out all
#' rows where the QAPPApprovedIndicator is 'Y'. If clean = FALSE, cleanNA = FALSE,
#' and flaggedonly = FALSE, the function will not make any changes to the data.
#'
#' Note: This is not a required field, so it is often left blank (NA) even if
#' the data has an associated QAPP. All states and tribes that collect
#' monitoring data using 106 funding (almost all state and tribal data in WQX)
#' are required to have an EPA approved QAPP to receive 106 funding. Therefore,
#' most of these organizations data has an approved QAPP even if the data
#' submitted to WQP is NA.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument with two possible values called "TRUE" and
#' "FALSE". When clean=TRUE, rows of data where the QAPPApprovedIndicator equals
#' "N" will be removed. When, clean=FALSE, rows of data where the
#' QAPPApprovedIndicator equals "N" will be retained.
#' @param cleanNA Boolean argument with two possible values called "TRUE" and
#' "FALSE". When cleanNA=TRUE, rows of data where the QAPPApprovedIndicator
#' equals "NA" will be removed. When, cleanNA=FALSE, rows of data where the
#' the QAPPApprovedIndicator equals "NA" will be retained.
#' @param flaggedonly Boolean argument; when flaggedonly = TRUE, the dataframe will
#' be filtered to remove any rows where the QAPPApprovedIndicator equals "Y".
#'
#' @return Several combinations of inputs are possible:
#' When clean = TRUE, cleanNA = FALSE, and flaggedonly = FALSE, the dataframe will
#' be filtered to show only rows where QAPPAprrovedIndicator is "Y" or "NA";
#' When clean = TRUE, cleanNA = TRUE, and flaggedonly = FALSE, the dataframe will
#' be filtered to show only rows where QAPPApprovedIndicator is "Y";
#' When clean = FALSE, cleanNA = TRUE, and flaggedonly = FALSE, the dataframe will
#' be filtered to show only rows where QAPPApprovedIndicator is "Y" or "N";
#' When clean = FALSE, cleanNA = FALSE, and flaggedonly = FALSE, no rows are
#' removed from the dataframe;
#' When clean = TRUE, cleanNA = TRUE, and flaggedonly = TRUE, the function will
#' not execute and an error message will be returned;
#' When clean = TRUE, cleanNA = FALSE, and flaggedonly = TRUE, the dataframe will
#' be filtered to show only rows where QAPPApprovedIndicator is "NA";
#' When clean = FALSE, cleanNA = TRUE, and flaggedonly = TRUE, the dataframe will
#' be filtered to show only rows where QAPPApprovedIndicator is "N";
#' When clean = FALSE, cleanNA = FALSE, and flaggedonly = TRUE, the dataframe will
#' be filtered to show only rows where QAPPApprovedIndicator is "N" or "NA"
#'
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' data(Data_Nutrients_UT)
#'
#' # Show data where the QAPPApprovedIndicator equals "Y" or "NA":
#' QAPPapproved_clean <- TADA_FindQAPPApproval(Data_Nutrients_UT)
#'
#' # Show only data where the QAPPApprovedIndicator equals "Y":
#' QAPPapproved_cleanNAs <- TADA_FindQAPPApproval(Data_Nutrients_UT, cleanNA = TRUE)
#'
#' # Show data where the QAPPApprovedIndicator equals "N" or "NA":
#' QAPPIndicator_N_NA <- TADA_FindQAPPApproval(Data_Nutrients_UT,
#' clean = FALSE,
#' cleanNA = FALSE, flaggedonly = TRUE
#' )
#'
#' # Show data where the QAPPApprovedIndicator equals "N":
#' QAPPIndicator_N <- TADA_FindQAPPApproval(Data_Nutrients_UT,
#' clean = FALSE,
#' cleanNA = TRUE, flaggedonly = TRUE
#' )
#'
#' # Note: When clean = FALSE, cleanNA = FALSE, and flaggedonly = FALSE, no data is removed
#' # Note: When clean = TRUE, cleanNA = TRUE, and flaggedonly = TRUE, an error message is returned
#'
TADA_FindQAPPApproval <- function(.data, clean = FALSE, cleanNA = FALSE, flaggedonly = FALSE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check cleanNA is boolean
TADA_CheckType(cleanNA, "logical")
# check flaggedonly is boolean
TADA_CheckType(flaggedonly, "logical")
# check .data has required columns
TADA_CheckColumns(.data, "QAPPApprovedIndicator")
# check that clean, cleanNA and flaggedonly are not all TRUE
if (clean == TRUE & cleanNA == TRUE & flaggedonly == TRUE) {
stop("Function not executed because clean, cleanNA, and flaggedonly cannot all be TRUE")
}
# execute function after checks are passed
# if flaggedonly = FALSE
if (flaggedonly == FALSE) {
if (clean == TRUE) {
.data <- dplyr::filter(.data, is.na(QAPPApprovedIndicator) == TRUE | QAPPApprovedIndicator == "Y")
if (nrow(.data) == 0) {
print("All QAPPApprovedIndicator data is N")
}
}
if (cleanNA == TRUE) {
.data <- dplyr::filter(.data, is.na(QAPPApprovedIndicator) == FALSE)
if (nrow(.data) == 0 & clean == TRUE) {
print("All QAPPApprovedIndicator data is NA or N")
} else if (nrow(.data) == 0 & clean == FALSE) {
print("All QAPPApprovedIndicator data is NA")
}
}
if (clean == FALSE & cleanNA == FALSE) {
print("Data is flagged but not removed because clean and cleanNA were FALSE")
}
.data <- TADA_OrderCols(.data)
return(.data)
}
# if flaggedonly = TRUE
if (flaggedonly == TRUE & clean == TRUE & cleanNA == FALSE) {
NA.data <- dplyr::filter(.data, is.na(QAPPApprovedIndicator) == TRUE)
if (nrow(NA.data) == 0) {
warning("All QAPPApprovedIndicator data is 'Y' or 'N'")
}
NA.data <- TADA_OrderCols(NA.data)
return(NA.data)
}
if (flaggedonly == TRUE & clean == FALSE & cleanNA == TRUE) {
N.data <- dplyr::filter(.data, QAPPApprovedIndicator == "N")
if (nrow(N.data) == 0) {
warning("All QAPPApprovedIndicator data is NA or 'Y'")
}
N.data <- TADA_OrderCols(N.data)
return(N.data)
}
if (flaggedonly == TRUE & clean == FALSE & cleanNA == FALSE) {
NAorN.data <- dplyr::filter(.data, is.na(QAPPApprovedIndicator) == TRUE | QAPPApprovedIndicator == "N")
if (nrow(NAorN.data) == 0) {
warning("All QAPPApprovedIndicator data is 'Y'")
}
NAorN.data <- TADA_OrderCols(NAorN.data)
return(NAorN.data)
}
}
#' Check if an approved QAPP document URL is provided
#'
#' Function checks data submitted under the "ProjectFileUrl" column
#' to determine if a QAPP document is available to review. When clean = FALSE,
#' a column will be appended to flag results that have an associated
#' QAPP document URL provided. When clean = TRUE, rows that do not
#' have an associated QAPP document are removed from the dataframe and no column
#' will be appended. This function should only be used to remove data if an
#' accompanying QAPP document is required to use data in assessments.
#'
#' @param .data TADA dataframe
#' @param clean Boolean argument; removes data without an associated QAPP
#' document from the dataframe when clean = TRUE. Default is clean = FALSE.
#'
#' @return Returns input dataframe with the added "TADA.QAPPDocAvailable" column.
#' When clean = FALSE, no data are removed and the TADA.QAPPDocAvailable column
#' flags rows with an associated QAPP document. When clean = TRUE,
#' data without an associated QAPP document are removed from the dataframe.
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' data(Data_Nutrients_UT)
#'
#' # Flag, but do not remove, data without an associated QAPP document in
#' # new column titled "TADA.QAPPDocAvailable":
#' FlagData_MissingQAPPDocURLs <- TADA_FindQAPPDoc(Data_Nutrients_UT)
#'
#' # Remove data without an associated QAPP document available:
#' RemoveData_MissingQAPPDocURLs <- TADA_FindQAPPDoc(Data_Nutrients_UT, clean = TRUE)
#'
TADA_FindQAPPDoc <- function(.data, clean = FALSE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check clean is boolean
TADA_CheckType(clean, "logical")
# check .data has required columns
# generate required column if it does not exist (there is no project data)
if ("ProjectFileUrl" %in% colnames(.data)) {
.data <- .data
} else {
# create empty ProjectFileUrl column
.data[, "ProjectFileUrl"] <- NA
}
# check .data has required columns
TADA_CheckColumns(.data, "ProjectFileUrl")
# default flag column
.data$TADA.QAPPDocAvailable <- "N"
# execute function after checks are passed
# flag data where QAPP document url is provided
# make QAPPdoc.data data frame
QAPPdoc.data <- dplyr::filter(.data, grepl("/", ProjectFileUrl))
NQAPPdoc.data <- subset(.data, !.data$ResultIdentifier %in% QAPPdoc.data$ResultIdentifier)
# if there is data without an associated QAPP url in the data set
if (nrow(QAPPdoc.data) != 0) {
# change flag column
QAPPdoc.data$TADA.QAPPDocAvailable <- "Y_ProjectFileUrlProvided"
# join QAPPdoc.data to flag.data
flag.data <- plyr::rbind.fill(QAPPdoc.data, NQAPPdoc.data)
# flagged output
if (clean == FALSE) {
flag.data <- TADA_OrderCols(flag.data)
return(flag.data)
}
# clean output
if (clean == TRUE) {
# remove data without an associated QAPP url
clean.data <- dplyr::filter(flag.data, grepl("/", ProjectFileUrl))
# remove TADA.QAPPDocAvailable column
# clean.data <- dplyr::select(clean.data, -TADA.QAPPDocAvailable)
clean.data <- TADA_OrderCols(clean.data)
return(clean.data)
}
}
# if no associated QAPP url data is in the data set
if (nrow(QAPPdoc.data) == 0) {
if (clean == FALSE) {
print("No QAPP document url data found in your dataframe. Returning input dataframe with TADA.QAPPDocAvailable column for tracking.")
.data <- TADA_OrderCols(.data)
return(.data)
}
if (clean == TRUE) {
print("This dataframe is empty because we did not find any QAPP document url data in your dataframe")
QAPPdoc.data <- TADA_OrderCols(QAPPdoc.data)
return(QAPPdoc.data)
}
}
}
#' Invalid coordinates
#'
#' This function identifies and flags invalid coordinate data. When
#' clean_outsideUSA = "no" and clean_imprecise = FALSE,
#' a column will be appended titled "TADA.InvalidCoordinates.Flag" with the following
#' flags: 1) If the latitude is less than zero, the row will be
#' flagged with "LAT_OutsideUSA" (with the exception of American Samoa,
#' Northern Mariana Islands, and Guam), 2) If the longitude is greater than zero AND less than 145,
#' the row will be flagged as "LONG_OutsideUSA" (with the exception of
#' American Samoa, Northern Mariana Islands, and Guam), and 3) Finally,
#' precision can be measured by the number of decimal places in the latitude and longitude
#' provided. If either the latitude or longitude does not have at least three numbers to the
#' right of the decimal point, the row will be flagged as "Imprecise". Occasionally
#' latitude and longitude measurements are flagged as outside of the United States
#' because the data was entered as negative when it should be positive or vice versa.
#' This function offers the option of clean_outsideUSA = "change sign" to fix this
#' issue. However, data owners should fix the raw data through WQX. For assistance
#' with changing raw data, email the WQX help desk: \email{WQX@@epa.gov}
#'
#' @param .data TADA dataframe
#' @param clean_outsideUSA Character argument with options "no", "remove", and "change sign";
#' flags coordinates as outside the USA when clean_outsideUSA = "no";
#' removes data with coordinates outside of the United States when clean_outsideUSA = "remove";
#' changes sign of lat/long coordinates flagged as outside the USA when
#' clean_outside = "change sign"; Default is clean_outsideUSA = "no".
#' @param clean_imprecise Boolean argument; removes imprecise data when