-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathUtilities.R
More file actions
2594 lines (2421 loc) · 79.1 KB
/
Utilities.R
File metadata and controls
2594 lines (2421 loc) · 79.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Silence Print Messages from Code Execution
#'
#' This utility function executes the provided code while suppressing any print messages.
#' It is useful for running code quietly, especially when print statements are not needed.
#'
#' @name quiet
#' @param x Expression or code block to execute silently.
#' @return The result of the executed code, with all print messages suppressed.
#'
quiet <- function(x) {
# Redirect output to a temporary file to suppress prints
sink(tempfile())
# Ensure sink is terminated on exit
on.exit(sink())
# Execute the code and return its result invisibly
invisible(force(x))
}
# write global variables. Gets rid of global variable NOTE in check:
utils::globalVariables(c(
"TADA.ResultValueAboveUpperThreshold.Flag",
"ActivityIdentifier",
"ActivityMediaName",
"ActivityStartDate",
"TADA.ResultValueBelowUpperThreshold.Flag",
"TADA.ResultValueBelowLowerThreshold.Flag",
"CharacteristicName",
"Conversion.Factor",
"Count",
"Description",
"FieldName",
"FieldValue",
"MethodSpecationName",
"MonitoringLocationIdentifier",
"OrganizationFormalName",
"OrganizationIdentifier",
"ProjectDescriptionText",
"ProjectFileUrl",
"ProjectIdentifier",
"ProjectMonitoringLocationWeightingUrl",
"ProjectName",
"QAPPApprovalAgencyName",
"QAPPApprovedIndicator",
"ResultDetectionConditionText",
"ResultMeasureValue",
"SamplingDesignTypeCode",
"Source",
"Status",
"TADA.ContinuousData.Flag",
"TADA.SuspectCoordinates.Flag",
"TADA.PotentialDupRowIDs.Flag",
"TADA.QAPPDocAvailable",
"Target.Unit",
"Type",
"Value.Unit",
"TADA.AnalyticalMethod.Flag",
"TADA.MethodSpeciation.Flag",
"TADA.ResultUnit.Flag",
"TADA.SampleFraction.Flag",
"YearSummarized",
"where",
"TADA.CharacteristicName",
"ResultIdentifier",
"TADA.ResultMeasureValue",
"n_sites",
"n_records",
"statecodes_df",
"STUSAB",
"ActivityStartTime.Time",
"numorgs",
"dup_id",
"LatitudeMeasure",
"TADA.ResultMeasureValueDataTypes.Flag",
"Name",
"TADA.Detection_Type",
"DetectionQuantitationLimitTypeName",
"TADA.Limit_Type",
"multiplier",
"summ",
"cf",
"LongitudeMeasure",
"TADA.CensoredData.Flag",
"Censored_Count",
"Status2",
"ActivityTypeCode",
"SampleCollectionEquipmentName",
"ResultTimeBasisText",
"StatisticalBaseCode",
"ResultValueTypeName",
"masked",
"TADA.env",
"Legend",
"Fields",
"desc",
"WQXActivityType_Cached",
"TADA.ActivityType.Flag",
"Code",
"ResultCount",
"tot_n",
"MonitoringLocationName",
"TADA.LatitudeMeasure",
"TADA.LongitudeMeasure",
"median",
"sd",
"TADA.ComparableDataIdentifier",
"roundRV",
"TADA.DuplicateID",
"maxRV",
"within10",
"AllGroups",
"Domain.Value.Status",
"Char_Flag",
"Comparable.Name",
"TADA.ResultMeasureValue1",
"TADA.ResultSampleFractionText",
"TADA.MethodSpeciationName",
"TADA.ResultMeasure.MeasureUnitCode",
"TADA.ActivityMediaName",
"TADA.NutrientSummationGroup",
"SummationName",
"SummationRank",
"SummationFractionNotes",
"SummationSpeciationNotes",
"SummationSpeciationConversionFactor",
"SummationNote",
"NutrientGroup",
"Target.Speciation",
"TADA.NearbySiteGroups",
"numres",
"TADA.SingleOrgDupGroupID",
"TADA.MeasureQualifierCode.Flag",
"TADA.MeasureQualifierCode.Def",
"MeasureQualifierCode",
"value",
"Flag_Column",
"ActivityStartDateTime",
"TADA.MultipleOrgDupGroupID",
"TADA.WQXVal.Flag",
"Concat",
"MeasureQualifierCode.Split",
"TADA.Media.Flag",
"ML.Media.Flag",
"Unique.Identifier",
"Domain",
"Note.Recommendation",
"Conversion.Coefficient",
"Last.Change.Date",
"Value",
"Minimum",
"Comb",
"CombList",
"TADA.Target.ResultMeasure.MeasureUnitCode",
"TADA.WQXUnitConversionFactor",
"TADA.WQXUnitConversionCoefficient",
"TADA.Target.MethodSpeciationName",
"flag",
"NConvert",
"MultUnits",
"CharList",
"CharUnit",
"SingleNearbyGroup",
"TADA.MultipleOrgDuplicate",
"TADA.ResultSelectedMultipleOrgs",
"Maximum",
"OBJECTID",
"GLOBALID",
"assessmentunitidentifier",
"index",
"epsg",
"ResultMeasure.MeasureUnitCode",
"TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode",
"NCode",
"ATTAINS.AssessmentUnitIdentifier",
"ATTAINS_AU",
"TOTALAREA_MI",
"TOTALAREA_KM",
"ATTAINS_AUs",
"ARD_Category",
"ActivityRelativeDepthName",
"DepthsByGroup",
"DepthsPerGroup",
"MeanResults",
"MonitoringLocationTypeName",
"N",
"SecchiConversion",
"TADA.ActivityBottomDepthHeightMeasure.MeasureValue",
"TADA.ActivityDepthHeightMeasure.MeasureUnitCode",
"TADA.ActivityDepthHeightMeasure.MeasureValue",
"TADA.CharacteristicsForDepthProfile TADA.ConsolidatedDepth",
"TADA.ConsolidatedDepth.Bottom TADA.ConsolidatedDepth.Unit",
"TADA.DepthCategory.Flag",
"TADA.DepthProfileAggregation.Flag",
"TADA.NResults",
"TADA.ResultDepthHeightMeasure.MeasureUnitCode",
"TADA.ResultDepthHeightMeasure.MeasureValue",
"YAxis.DepthUnit",
"TADA.CharacteristicsForDepthProfile",
"TADA.ConsolidatedDepth",
"TADA.ConsolidatedDepth.Bottom",
"TADA.ConsolidatedDepth.Unit",
"col2rgb",
"palette.colors",
"rect",
"rgb",
"text",
"CodeNoSpeciation",
"ResultMeasure.MeasureUnitCode.Upper",
"TADA.MonitoringLocationIdentifier",
"StringA",
"StringB",
"MeasureUnitCode.match",
"TADA.ActivityTopDepthHeightMeasure.MeasureValue",
"group_id",
"time_diff_lead",
"time_diff_lag",
"NResults",
"missing.group",
"TADA.PairingGroup",
"TADA.PairingGroup.Rank",
"timediff",
"TADA.MonitoringLocationName",
"TADA.MonitoringLocationTypeName",
"ATTAINS.SubmissionId",
"HorizontalCoordinateReferenceSystemDatumName",
"NCount",
"NHD.catchmentareasqkm",
"NHD.comid",
"NHD.nhdplusid",
"NHD.resolution",
"areasqkm",
"assessmentUnitIdentifier",
"catchmentareasqkm",
"comid",
"featureid",
"geometry",
"nhdplusid",
"waterTypeCode",
"TADA.NearbySiteGroup",
"TADA.MonitoringLocationIdentifier.New",
"TADA.NearbySites.Flag",
"CountSites",
"Group",
"Matrix",
"n_id",
"OrgRank",
"rank.default",
"Site",
"TADA.LatitudeMeasure.New",
"TADA.LongitudeMeasure.New",
"TADA.MonitoringLocationName.New",
"TADA.MonitoringLocationTypeName.New",
"df_number",
"ASSESSMENT_UNIT_ID",
"ATTAINS.FlagParameterName",
"ATTAINS.FlagUseName",
"ATTAINS.ParameterName",
"CRITERIATYPEAQUAHUMHLTH",
"CRITERIATYPEFRESHSALTWATER",
"CRITERIATYPE_ACUTECHRONIC",
"CRITERIATYPE_WATERORG",
"CRITERION_VALUE",
"ENTITY_ABBR",
"EPA304A.PollutantName",
"IncludeOrExclude",
" MONITORING_DATA_LINK_TEXT",
"MONITORING_DATA_LINK_TEXT.New",
"MS_LOCATION_ID",
"MS_ORG_ID",
"MonitoringDataLinkText",
"OrgIDForURL",
"POLLUTANT_NAME",
"ProviderName",
"TADA.SingleOrgDup.Flag",
"UNIT_NAME",
"URLencode",
"USE_CLASS_NAME_LOCATION_ETC",
"assessment_unit_identifier",
"monitoring_data_link_text",
"monitoring_location_identifier",
"monitoring_organization_identifier",
"monitoring_stations",
"organization_identifier",
"organization_identifier.y",
"parameter",
"use_name",
"use_name.y",
"ATTAINS.OrganizationIdentifier",
"ATTAINS.ParameterName.y",
"ATTAINS.UseName",
"ATTAINS.UseName.x",
"ATTAINS.UseName.y",
"Flag.ParameterInput",
"Flag.UseInput",
"TADA.ComparableDataIdentifier.x",
"TADA.ComparableDataIdentifier.y",
"organizationId",
"organizationName",
"organizationType",
"parameterName",
"PARCEL_NO",
"TRIBE_NAME",
"everything",
"resultCount",
"tribal_area",
"txtProgressBar",
"Date",
"NWIS.parameter",
"NWIS.status",
"NWIS.value",
"TADA.DistanceAway.Meters",
"agency_cd begin_date",
"parm_cd site_no",
"site_tp_cd",
"site_type",
"st_drop_geometry",
"station_nm",
"ApplyUniqueSpatialCriteria",
"assessmentUnitId",
"ATTAINS.AssessmentUnitName",
"ATTAINS.OrganizationIdentifier",
"ATTAINS.WaterType",
"useName",
"waterType",
"TADA.AssessmentUnitStatus",
"Flag.AssessmentNote",
"cluster",
"count",
"count_nu",
"data_type",
"data_type_cd",
"dec_lat_va",
"dec_long_va",
"end_date",
"parameter_code",
"parameter_name_description",
"Statistic Type Code",
"Statistic Type Description",
"agency_cd",
"begin_date",
"parm_cd",
"site_no",
"stat_cd",
"stat_type",
"grouped.sites",
"n",
"nearby",
"rainbow",
"monitoringLocationId",
"monitoringLocationOrgId",
"monitoringLocationDataLink",
"ATTAINS.OrganizationName",
"ATTAINS.WaterType",
"ATTAINS.MonitoringDataLinkText",
"ATTAINS.MonitoringDataLinkText.New",
"ATTAINS.MonitoringLocationIdentifier",
"AssessmentUnitIdentifier",
"DetectionQuantitationLimitMeasure.MeasureUnitCode",
"MS_DATA_LINK",
"OLD_ATTAINS.MonitoringLocationIdentifier",
"Shape_Area",
"Shape_Length",
"TADA.AURefSource",
"TADA.NutrientSummation.Flag",
"assessmentunitname",
"assmnt_joinkey",
"catchmentistribal",
"catchmentresolution",
"catchmentstatecode",
"has4bplan",
"hasalternativeplan",
"hasprotectionplan",
"hastmdl",
"huc12",
"ircategory",
"isassessed",
"isimpaired",
"isthreatened",
"objectId",
"on303dlist",
"organizationid",
"organizationname",
"orgtype",
"overallstatus",
"permid_joinkey",
"region",
"reportingCycle",
"reportingcycle",
"response.code",
"return_sf",
"state",
"submissionid",
"tas303d",
"visionpriority303d",
"waterbodyreportlink",
"xwalk_huc12_version",
"xwalk_method",
"WqxV2.FieldName",
"auid.col",
"ml.col",
"type.col",
"AggregatedActivityEndDateTime",
"AggregatedActivityStartDateTime",
"ATTAINS.AssessmentUnitIdentifier.y",
"ATTAINS.WaterType.y DepthCategory",
"DurationPeriod.x",
"DurationValue",
"geomean_TADA.ResultMeasureValue",
"MagnitudeUnit",
"MagnitudeValueLower",
"MagnitudeValueUpper",
"n_Aggregatedsamples",
"n_exceedance",
"SaltFresh",
"TADA.ParameterInSite.Flag",
"UniqueSpatialCriteria",
"ATTAINS.WaterType.y",
"DepthCategory",
"User.WaterType",
"ATTAINS.OrganizationId",
"MatchMessage",
"Mismatch",
"Ref.WaterType",
"Alias.Type.Name",
"CAS_NO",
"Char_Flag.x",
"Char_Flag.y",
"Characteristic.Name",
"STD_POLLUTANT_NAME",
"name",
"name_words",
"percent_match_ATTAINS",
"percent_match_WQX",
"Characteristic",
"WQXcharValRef",
"CAS.Number",
"CAS_NO",
"CharacteristicName.x",
"CharacteristicName.y",
"Comparable.Name.x",
"Comparable.Name.y",
"POLLUTANT_NAME.x",
"POLLUTANT_NAME.y",
"STD_POLLUTANT_NAME.x",
"STD_POLLUTANT_NAME.y",
"percent_match_ATTAINS_CST",
"percent_match_ATTAINS_WQX",
"percent_match_CST",
"UserRef.AssessmentUnitIdentifier",
"Group.n",
"Ref.TADA.Media.Flag",
"context2",
"CST.STD_POLLUTANT_NAME",
"ENTITY_NAME",
"TADA.NearbySiteGroup.New",
"code",
"context",
"ATTAINS_catchments",
"attains.imgs",
"attains.labels",
"icon.labels",
"ATTAINS.ParameterName.x",
"Ref.AssessmentUnitIdentifier",
"Alias.Name",
"CST.SourceLink",
"CST.StdPollutantName",
"CST_CAS_NO",
"PDFPGNO",
"SOURCE",
"WQXCharAliasRef",
"WQX_CAS_NO",
"percent_match_CST_ATTAINS",
"percent_match_CST_WQX",
"percent_match_WQX_ATTAINS",
"percent_match_WQX_CST",
"review",
"source.y"
))
# global variables for tribal feature layers used in TADA_OverviewMap in Utilities.R
AKAllotmentsUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/0/query"
AKVillagesUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/1/query"
AmericanIndianUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/2/query"
OffReservationUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/3/query"
OKTribeUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/4/query"
VATribeUrl <- "https://geopub.epa.gov/arcgis/rest/services/EMEF/Tribal/MapServer/5/query"
#' Calculate Decimal Places
#'
#' This function calculates the number of decimal places in a numeric value.
#' It returns the number of digits to the right of the decimal point for numeric data.
#'
#' @param x A numeric value or vector from the TADA profile.
#'
#' @return An integer representing the number of decimal places in the numeric value.
#' If the input is an integer or a numeric value with no decimal places, the function returns 0.
TADA_DecimalPlaces <- function(x) {
# Convert the number to a character string, remove trailing zeros, and split by the decimal point
parts <- strsplit(sub("0+$", "", as.character(x)), ".", fixed = TRUE)[[1]]
# If there is a decimal part, return its length; otherwise, return 0
if (length(parts) > 1) {
return(nchar(parts[[2]]))
} else {
return(0)
}
}
#' Check Type
#'
#' This function checks if the inputs to a function are of the expected type. It
#' is used at the beginning of TADA functions to ensure the inputs are suitable.
#'
#' @param arg An input argument to check
#' @param type Expected class of input argument
#' @param paramName Optional name for argument to use in error message
TADA_CheckType <- function(arg, type, paramName = deparse(substitute(arg))) {
if (!inherits(arg, type)) {
errorMessage <- sprintf("%s must be of class '%s'", paramName, type)
stop(errorMessage)
}
invisible(NULL)
}
#' Check Columns
#'
#' This function checks if the expected column names are in the dataframe. It is
#' used at the beginning of TADA functions to ensure the input data frame is
#' suitable (i.e. is either the full physical/chemical results profile
#' downloaded from WQP or the TADA profile template downloaded from the EPA TADA
#' webpage.)
#'
#' @param .data A dataframe
#' @param expected_cols A vector of expected column names as strings
#' @return Invisible `NULL` if all expected columns are present; otherwise, an error is thrown.
TADA_CheckColumns <- function(.data, expected_cols) {
TADA_CheckType(.data, "data.frame", "Input object") # check .data is data.frame
if (!is.vector(expected_cols) || !is.character(expected_cols)) {
stop("Expected columns must be a character vector.")
}
missing_cols <- setdiff(expected_cols, colnames(.data))
if (length(missing_cols) > 0) {
stop(paste(
"The dataframe does not contain the required field(s):",
paste(missing_cols, collapse = ", "),
". Use either the full physical/chemical profile downloaded from WQP or download the TADA profile template available on the EPA TADA webpage."
))
}
invisible(NULL)
}
#' TADA_ConvertSpecialChars
#'
#' This function will screen a column of the user's choice for special
#' characters. It creates a NEW column that describes the content of the column
#' prior to conversion to numeric (named "TADA.COLUMN NAME DataTypes.Flag"). It
#' also creates a NEW column to hold the new, numeric format (named "TADA.COLUMN
#' NAME"). This function will successfully convert some special character
#' formats to numeric: whitespace, >, <, ~, %, and commas are removed before
#' converting a result value to numeric. Result values in the format # - # are
#' converted to an average of the two numbers. Result values
#' containing any other text or non-numeric characters become NA in
#' the newly created "TADA.COLUMN NAME" and labeled accordingly in "TADA.COLUMN
#' NAME DataTypes.Flag". When clean = TRUE, rows that cannot be converted to
#' numeric are removed. When clean = FALSE, no rows are removed. Default is
#' clean = FALSE. When flaggedonly = TRUE, data frame is filtered to show only
#' rows with non-numeric result values. Default is flaggedonly = FALSE.
#'
#'
#' @param .data A TADA profile object
#' @param col A character column to be converted to numeric
#' @param clean Boolean argument; removes non-numeric result values from the
#' data frame when clean = TRUE. Default is clean = FALSE.
#' @param flaggedonly Boolean argument; filters dataframe to show only
#' non-numeric result values when flaggedonly = TRUE. Default is flaggedonly
#' = FALSE.
#' @param percent.ave Boolean argument; default is percent.ave = TRUE. When
#' clean = TRUE, any percent range values will be averaged. When
#' percent.ave = FALSE, percent range values are not averaged, but are flagged.
#'
#' @return Returns the original dataframe with two new columns: the input column
#' with the prefix "TADA.", which holds the numeric form of the original column,
#' and "TADA.COLUMN NAME DataTypes.Flag", which has text describing the type of
#' data contained within the column of interest, including "Numeric",
#' "Less Than" (<), "Greater Than" (>), "Approximate Value" (~), "Text" (A-z),
#' "Percentage" (%), "Comma-Separated Numeric" (#,###), and
#' "Numeric Range - Averaged" (# - #).
#'
#' @export
#'
#' @examples
#' HandleSpecialChars_ResultMeasureValue <-
#' TADA_ConvertSpecialChars(Data_Nutrients_UT, "ResultMeasureValue")
#' unique(HandleSpecialChars_ResultMeasureValue$
#' TADA.ResultMeasureValueDataTypes.Flag)
#'
#' HandleSpecialChars_DetLimMeasureValue <-
#' TADA_ConvertSpecialChars(
#' Data_Nutrients_UT,
#' "TADA.DetectionQuantitationLimitMeasure.MeasureValue"
#' )
#' unique(HandleSpecialChars_DetLimMeasureValue$
#' TADA.DetectionQuantitationLimitMeasure.MeasureValueDataTypes.Flag)
TADA_ConvertSpecialChars <- function(
.data,
col,
percent.ave = TRUE,
clean = FALSE,
flaggedonly = FALSE
) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# Check if the input data frame is empty
if (nrow(.data) == 0) {
message("The entered data frame is empty. The function will not run.")
return(NULL) # Exit the function early
}
if (!col %in% names(.data)) {
stop("Suspect column name specified for input dataset.")
}
# 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"
)
}
if (!any(grepl("TADA.", col))) {
# Define new column names
numcol <- paste0("TADA.", col)
flagcol <- paste0("TADA.", col, "DataTypes.Flag")
# Create dummy columns for easy handling in function
chars.data <- .data
names(chars.data)[names(chars.data) == col] <- "orig"
chars.data <- chars.data |>
dplyr::select(-tidyselect::any_of(c(col, numcol, flagcol)))
chars.data$masked <- chars.data$orig
# Add percentage character to dissolved oxygen saturation ResultMeasureValue
# so percentage and percentage - range averaged can be identified correctly
if (col == "ResultMeasureValue") {
do.units <- c("%", "% SATURATN")
chars.data$masked <- ifelse(
chars.data$CharacteristicName == "Dissolved oxygen (DO)" &
chars.data$ResultMeasure.MeasureUnitCode %in% do.units,
paste(chars.data$masked, "%"),
chars.data$masked
)
# updates percentage units where NA
chars.data$TADA.ResultMeasure.MeasureUnitCode <- ifelse(
grepl("%", chars.data$masked),
"%",
chars.data$ResultMeasure.MeasureUnitCode
)
# TADA.ResultMeasure.MeasureUnitCode to uppercase
chars.data$TADA.ResultMeasure.MeasureUnitCode <- toupper(
chars.data$TADA.ResultMeasure.MeasureUnitCode
)
}
# If column is already numeric, just discern between NA and numeric
if (is.numeric(chars.data$orig)) {
clean.data <- chars.data |>
dplyr::mutate(
flag = dplyr::case_when(
is.na(masked) ~ as.character("NA - Not Available"),
TRUE ~ as.character("Numeric")
)
)
} else {
chars.data$masked <- gsub(" ", "", chars.data$masked) # get rid of white space for subsequent sorting
# Detect special characters in column and populate new flag column with descriptor
# of the specific type of character/data type
clean.data <- chars.data |>
dplyr::mutate(
flag = dplyr::case_when(
is.na(masked) ~ as.character("NA - Not Available"),
(!is.na(
suppressWarnings(as.numeric(masked)) == TRUE
)) ~ as.character("Numeric"),
(grepl("<", masked) == TRUE) ~ as.character("Less Than"),
(grepl(">", masked) == TRUE) ~ as.character("Greater Than"),
(grepl("\\+", masked) == TRUE) ~ as.character("Greater Than"),
(grepl("~", masked) == TRUE) ~ as.character("Approximate Value"),
(grepl("[A-Za-z]", masked) == TRUE) ~ as.character("Text"),
(grepl("%", masked) == TRUE) ~ as.character("Percentage"),
(grepl(",", masked) == TRUE) ~ as.character(
"Comma-Separated Numeric"
),
(grepl("\\d\\-\\d", masked) == TRUE) ~ as.character(
"Numeric Range - Averaged"
),
(grepl("([1-9]|[1-9][0-9]|100)-([1-9]|[1-9][0-9]|100)%", masked) ==
TRUE) ~ as.character("Percentage Range - Averaged"),
# because * is a special character you have to escape\\ it:
(grepl("\\*", masked) == TRUE) ~ as.character("Approximate Value"),
(!stringi::stri_enc_mark(masked) %in% c("ASCII")) ~ as.character(
"Non-ASCII Character(s)"
),
TRUE ~ "Coerced to NA"
),
flag = ifelse(
flag == "Greater Than" & grepl("%", masked) & grepl("-", masked),
"Percentage Range - Averaged",
flag
),
flag = ifelse(
flag == "Less Than" & grepl("%", masked) & grepl("-", masked),
"Percentage Range - Averaged",
flag
)
)
}
if (percent.ave == FALSE) {
num.range.filter <- c("Numeric Range - Averaged")
}
if (percent.ave == TRUE) {
num.range.filter <- c(
"Numeric Range - Averaged",
"Percentage Range - Averaged"
)
}
# Result Values that are numeric ranges with the format #-# are converted to an average of the two numbers expressed in the range.
if (any(clean.data$flag %in% num.range.filter)) {
numrange <- subset(clean.data, clean.data$flag %in% num.range.filter)
notnumrange <- subset(clean.data, !clean.data$flag %in% num.range.filter)
numrange <- numrange |>
dplyr::mutate(
masked = stringr::str_remove(masked, "[1-9]\\)"),
masked = stringr::str_remove(masked, "%"),
masked = stringr::str_remove(masked, ">"),
masked = stringr::str_remove(masked, "<")
) |>
tidyr::separate(
masked,
into = c("num1", "num2"),
sep = "-",
remove = TRUE
) |>
dplyr::mutate_at(c("num1", "num2"), as.numeric)
numrange$masked <- as.character(rowMeans(
numrange[, c("num1", "num2")],
na.rm = TRUE
))
numrange <- numrange[, !names(numrange) %in% c("num1", "num2")] |>
dplyr::mutate(
masked = ifelse(
flag == "Percentage Range - Average",
paste(masked, "%", sep = ""),
masked
)
)
clean.data <- plyr::rbind.fill(notnumrange, numrange)
}
# In the new TADA column, convert to numeric and remove some specific special
# characters.
clean.data$masked <- suppressWarnings(as.numeric(stringr::str_replace_all(
clean.data$masked,
c(
"<" = "",
">" = "",
"~" = "",
"%" = "",
"\\*" = "",
"1\\)" = "",
"\\+" = ""
)
)))
# this updates the DataTypes.Flag to "NA - Not Available" if flag is NA
clean.data$flag <- ifelse(
is.na(clean.data$flag),
"NA - Not Available",
clean.data$flag
)
# remove columns to be replaced
clean.data <- clean.data |>
dplyr::select(
!(tidyselect::any_of(numcol)),
!(tidyselect::any_of(flagcol))
)
# Rename to original column name, TADA column name, and flag column name
names(clean.data)[names(clean.data) == "orig"] <- col
names(clean.data)[names(clean.data) == "masked"] <- numcol
names(clean.data)[names(clean.data) == "flag"] <- flagcol
clean.data <- TADA_OrderCols(clean.data)
} else {
flagcol <- paste0(col, "DataTypes.Flag")
numcol <- col
clean.data <- .data
# this updates the flagcol to "NA - Not Available" if numcol is NA
clean.data[[flagcol]] <- ifelse(
is.na(clean.data[[numcol]]),
"NA - Not Available",
clean.data[[flagcol]]
)
# remove columns to be replaced
clean.data <- clean.data |>
dplyr::select(
!(tidyselect::any_of(numcol)),
!(tidyselect::any_of(flagcol))
)
# Rename to original column name, TADA column name, and flag column name
names(clean.data)[names(clean.data) == "orig"] <- col
names(clean.data)[names(clean.data) == "masked"] <- numcol
names(clean.data)[names(clean.data) == "flag"] <- flagcol
clean.data <- TADA_OrderCols(clean.data)
}
if (flaggedonly == FALSE) {
if (clean == TRUE) {
clean.data <- clean.data |>
dplyr::filter(
!(!!rlang::sym(flagcol)) %in%
c(
"NA - Not Available",
"Text",
"Non-ASCII Character(s)",
"Result Value/Unit Cannot Be Estimated From Detection Limit",
"Coerced to NA"
)
)
return(clean.data)
}
if (clean == FALSE) {
return(clean.data)
}
}
if (flaggedonly == TRUE) {
clean.data <- clean.data |>
dplyr::filter(
!!rlang::sym(flagcol) %in%
c(
"NA - Not Available",
"Text",
"Non-ASCII Character(s)",
"Result Value/Unit Cannot Be Estimated From Detection Limit",
"Coerced to NA"
)
)
}
}
#' Substitute Preferred Characteristic Name for Deprecated Names
#'
#' This function uses the WQX Characteristic domain table to substitute
#' deprecated (i.e. retired and/or suspect) Characteristic Names with the new
#' name in the TADA.CharacteristicName column. TADA_SubstituteDeprecatedChars is
#' run within TADA_AutoClean, which runs within TADA_DataRetrieval and
#' (if autoclean = TRUE) in TADA_BigDataRetrieval. Therefore, deprecated
#' characteristic names are harmonized to the new name automatically upon data
#' retrieval. TADA_SubstituteDeprecatedChars can also be used by itself on a
#' user supplied dataset that is in the WQX/WQP format, if desired. This
#' solution works for both EPA WQX and USGS NWIS provided data.
#'
#' Enter ?TADA_GetCharacteristicRef() to review a list of all WQX
#' characteristics, the including deprecated names (Char_Flag). This can be
#' used as a crosswalk between the deprecated names (CharacteristicName) and
#' their new names (Comparable.Name).
#'
#' @param .data TADA dataframe
#' @param quiet logical; suppress messages if TRUE
#'
#' @return Input TADA dataframe with substituted characteristic names in
#' TADA.CharacteristicName column. Original columns are unchanged.
#'
#' @export
#'
#' @examples
#' \dontrun{
#' # download nutrient data in MT from 2022 and set autoclean = FALSE
#' df <- TADA_DataRetrieval(
#' startDate = "2022-01-01",
#' endDate = "2022-12-31",
#' characteristicType = "Nutrient",
#' statecode = "MT",
#' applyautoclean = FALSE, ask = FALSE
#' )
#' df2 <- TADA_SubstituteDeprecatedChars(df)
#' # in this example, "Inorganic nitrogen (nitrate and nitrite)" is a USGS NWIS
#' # characteristic that is deprecated and
#' # "Phosphate-phosphorus***retired***use Total Phosphorus, mixed forms"
#' # is a deprecated WQX name. Both are are transformed to their new names.
#' # review characteristic names before and after transformation
#' unique(df2$CharacteristicName)
#' unique(df2$TADA.CharacteristicName)
#'
#' df3 <- TADA_DataRetrieval(
#' startDate = "2022-01-01", endDate = "2022-12-31",
#' characteristicType = "Nutrient", statecode = "WY", applyautoclean = FALSE,
#' ask = FALSE
#' )
#' df4 <- TADA_SubstituteDeprecatedChars(df3)
#' unique(df4$CharacteristicName)
#' unique(df4$TADA.CharacteristicName)
#' }
TADA_SubstituteDeprecatedChars <- function(.data, quiet = FALSE) {
# Ensure required column
TADA_CheckColumns(.data, c("CharacteristicName"))
# Handle empty input
if (nrow(.data) == 0) {
if (!quiet) {
message(
"The entered data frame is empty. Skipping deprecated-name substitution."
)
}
return(.data)
}
# Ensure TADA.CharacteristicName exists (initialize uppercase)
if (!"TADA.CharacteristicName" %in% colnames(.data)) {
.data$TADA.CharacteristicName <- toupper(.data$CharacteristicName)
}
# Load the characteristic domain table
char.table <- TADA_GetCharacteristicRef()
# NWIS-friendly variant: trim at first '*' for retired WQX names
nwis_table <- char.table |>
dplyr::filter(
Char_Flag == "Deprecated",
grepl("retired", CharacteristicName, ignore.case = TRUE)
) |>
dplyr::mutate(
CharacteristicName = trimws(stringr::str_split(
CharacteristicName,
"\\*",
simplify = TRUE
)[, 1])
)
# Build reference table of deprecated names; select only needed columns and de-duplicate
ref.table <- char.table |>
dplyr::filter(Char_Flag %in% c("Deprecated")) |> # add "Suspect" here if desired
dplyr::bind_rows(nwis_table) |>
dplyr::select(CharacteristicName, Char_Flag, Comparable.Name) |>
dplyr::distinct(CharacteristicName, .keep_all = TRUE)
# Left-join on CharacteristicName only; preserve row order
.data <- dplyr::left_join(.data, ref.table, by = "CharacteristicName")
# Substitute deprecated names when Comparable.Name is present and non-empty
.data$TADA.CharacteristicName <- ifelse(
!is.na(.data$Char_Flag) &
!is.na(.data$Comparable.Name) &
nzchar(trimws(.data$Comparable.Name)),
.data$Comparable.Name,
.data$TADA.CharacteristicName
)
# Enforce uppercase for all values in TADA.CharacteristicName
.data$TADA.CharacteristicName <- toupper(.data$TADA.CharacteristicName)
# Reporting (respect quiet)
total_deprecated <- sum(!is.na(.data$Char_Flag))
changed_rows <- .data |>
dplyr::filter(
!is.na(Char_Flag),
!is.na(Comparable.Name),
nzchar(trimws(Comparable.Name))
)
changed_n <- nrow(changed_rows)
if (!quiet) {
if (changed_n > 0) {
# Unique mapping of original -> substituted (uppercase) names
mapping_df <- changed_rows |>
dplyr::distinct(CharacteristicName, TADA.CharacteristicName)
mapping_pairs <- paste0(
mapping_df$CharacteristicName,