Repository navigation
Expand file tree
/
Copy pathUnitConversions.R
More file actions
1322 lines (1198 loc) · 46.1 KB
/
Copy pathUnitConversions.R
File metadata and controls
1322 lines (1198 loc) · 46.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
#' Generate A DataFrame of Units and Target by Characteristic Name
#'
#' Creates a dataframe of unique characteristic/unit pairs and fills target unit
#' and conversion factors where possible. This reference can be edited and used
#' by TADA_ConvertResultUnits to standardize units by characteristic.
#'
#' Notes:
#' - Handles both prefixed and unprefixed unit columns (TADA.ResultMeasure.MeasureUnitCode
#' and ResultMeasure.MeasureUnitCode). Internally normalizes to the TADA-prefixed name.
#' - Incorporates units observed only in detection-limit fields to support
#' censored-data workflows.
#' - USGS unit synonyms (including units with speciation embedded) are
#' normalized via TADA_GetUSGSSynonymRef. This facilitates moving speciation
#' from units to TADA.MethodSpeciationName in TADA_ConvertResultUnits.
#' - WQX unit reference (TADA_GetMeasureUnitRef) provides default conversions,
#' while TADA priority references (TADAPriorityCharUnitRef.csv and
#' TADAPriorityCharConvertRef.csv) allow characteristic-specific targets and
#' conversions that can override WQX defaults when necessary.
#' - For characteristics with multiple target units (e.g., fundamentally
#' different unit families), an informational message is displayed in the console.
#'
#' The columns created by TADA_AutoClean are required to run this function. If
#' they are not present in the dataframe, TADA_AutoClean is automatically run
#' before the unit reference dataframe is created.
#'
#' @param .data TADA dataframe
#' @param message Logical. If TRUE (default), prints a message listing any
#' characteristics (TADA.CharacteristicName) that have more than one target unit.
#'
#' @return A dataframe with the following columns:
#' - TADA.CharacteristicName
#' - ResultMeasure.MeasureUnitCode (if available in the input; optional)
#' - TADA.ResultMeasure.MeasureUnitCode (normalized canonical name)
#' - TADA.Target.ResultMeasure.MeasureUnitCode
#' - TADA.WQXUnitConversionFactor
#' - TADA.WQXUnitConversionCoefficient
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' utils::data(Data_Nutrients_UT)
#' # Create a unit reference dataframe
#' UT_UnitRef <- TADA_CreateUnitRef(Data_Nutrients_UT)
TADA_CreateUnitRef <- function(.data, message = TRUE) {
# Create dataframe of unique combinations via helper.
# NOTE: TADA_UniqueCharUnitSpeciation normalizes/guards optional columns.
data.units <- TADA_UniqueCharUnitSpeciation(.data)
# If helper returns NULL (empty input), return a typed empty df (no error downstream).
if (is.null(data.units)) {
return(data.frame(
TADA.CharacteristicName = character(),
ResultMeasure.MeasureUnitCode = character(),
TADA.ResultMeasure.MeasureUnitCode = character(),
TADA.Target.ResultMeasure.MeasureUnitCode = character(),
TADA.WQXUnitConversionFactor = numeric(),
TADA.WQXUnitConversionCoefficient = numeric(),
stringsAsFactors = FALSE
))
}
# Remove method speciation only if present; not all upstream flows include it.
if ("TADA.MethodSpeciationName" %in% names(data.units)) {
data.units <- dplyr::select(data.units, -TADA.MethodSpeciationName)
}
# USGS synonyms: normalize units where speciation is embedded in the unit code.
usgs.ref <- TADA_GetUSGSSynonymRef()
usgs.ref$Target.Unit <- toupper(usgs.ref$Target.Unit)
usgs.unit <- usgs.ref |>
dplyr::select(Code, CodeNoSpeciation) |>
dplyr::mutate(
TADA.ResultMeasure.MeasureUnitCode = toupper(Code),
CodeNoSpeciation = toupper(CodeNoSpeciation)
) |>
dplyr::select(-Code)
# Add USGS normalization to data units.
data.units <- data.units |>
dplyr::left_join(usgs.unit, by = "TADA.ResultMeasure.MeasureUnitCode") |>
dplyr::mutate(
MeasureUnitCode.match = dplyr::if_else(
!is.na(CodeNoSpeciation),
CodeNoSpeciation,
TADA.ResultMeasure.MeasureUnitCode
)
) |>
dplyr::select(-CodeNoSpeciation)
rm(usgs.ref, usgs.unit)
# WQX unit reference for default conversions (broad coverage).
wqx.ref <- TADA_GetMeasureUnitRef()
wqx.ref <- wqx.ref |>
dplyr::select(
Code,
Target.Unit,
Conversion.Factor,
Conversion.Coefficient
) |>
dplyr::mutate(
Target.Unit = toupper(Target.Unit),
Conversion.Coefficient = dplyr::if_else(
is.na(Conversion.Coefficient),
0,
Conversion.Coefficient
),
MeasureUnitCode.match = toupper(Code)
) |>
dplyr::rename(TADA.Target.ResultMeasure.MeasureUnitCode = Target.Unit) |>
dplyr::select(
MeasureUnitCode.match,
TADA.Target.ResultMeasure.MeasureUnitCode,
Conversion.Factor,
Conversion.Coefficient
)
# TADA characteristic-specific target units (priority list).
tada.char.ref <- utils::read.csv(system.file(
"extdata",
"TADAPriorityCharUnitRef.csv",
package = "EPATADA"
))
tada.char.ref$TADA.Target.ResultMeasure.MeasureUnitCode <- toupper(
tada.char.ref$TADA.Target.ResultMeasure.MeasureUnitCode
)
tada.char.ref$TADA.CharacteristicName <- toupper(
tada.char.ref$TADA.CharacteristicName
)
# TADA-specific conversions overriding WQX where needed (created 4/30/2024).
file_path <- system.file(
"extdata",
"TADAPriorityCharConvertRef.csv",
package = "EPATADA"
)
if (file.exists(file_path)) {
tada.unit.ref <- readr::read_csv(
file_path,
col_types = readr::cols(
Code = readr::col_character(),
Last.Change.Date = readr::col_character(),
Target.Unit = readr::col_character(),
Conversion.Factor = readr::col_double(),
Conversion.Coefficient = readr::col_double()
),
show_col_types = FALSE
)
} else {
stop("File not found: TADAPriorityCharConvertRef.csv")
}
# Normalize codes and targets for joining.
tada.unit.ref <- tada.unit.ref |>
dplyr::mutate(
TADA.Target.ResultMeasure.MeasureUnitCode = toupper(Target.Unit),
TADA.ResultMeasure.MeasureUnitCode = toupper(Code)
) |>
dplyr::rename(MeasureUnitCode.match = TADA.ResultMeasure.MeasureUnitCode) |>
dplyr::select(-Target.Unit, -Code, -Last.Change.Date)
# Characteristic-specific targets with TADA conversions (preferred over WQX).
tada.targets <- data.units |>
dplyr::left_join(
tada.char.ref,
by = "TADA.CharacteristicName",
relationship = "many-to-many"
) |>
dplyr::filter(!is.na(TADA.Target.ResultMeasure.MeasureUnitCode)) |>
dplyr::left_join(
tada.unit.ref,
by = c(
"MeasureUnitCode.match",
"TADA.Target.ResultMeasure.MeasureUnitCode"
),
relationship = "many-to-many"
) |>
dplyr::mutate(
CharUnit = paste(
TADA.CharacteristicName,
"_",
TADA.ResultMeasure.MeasureUnitCode,
sep = ""
)
) |>
dplyr::filter(!is.na(Conversion.Factor)) |>
# NOTE: ResultMeasure.MeasureUnitCode column is optional; guard selection.
dplyr::select(dplyr::any_of(c(
"TADA.CharacteristicName",
"TADA.ResultMeasure.MeasureUnitCode",
"TADA.Target.ResultMeasure.MeasureUnitCode",
"ResultMeasure.MeasureUnitCode",
"Conversion.Factor",
"Conversion.Coefficient",
"CharUnit"
)))
rm(tada.char.ref, tada.unit.ref)
# Remaining pairs with WQX conversions where TADA-specific not provided.
tada.wqx <- data.units |>
dplyr::mutate(
CharUnit = paste(
TADA.CharacteristicName,
"_",
TADA.ResultMeasure.MeasureUnitCode,
sep = ""
)
) |>
dplyr::filter(!CharUnit %in% tada.targets$CharUnit) |>
dplyr::left_join(
wqx.ref,
by = c("MeasureUnitCode.match"),
relationship = "many-to-many"
) |>
dplyr::filter(!is.na(Conversion.Factor)) |>
dplyr::select(dplyr::any_of(c(
"TADA.CharacteristicName",
"TADA.ResultMeasure.MeasureUnitCode",
"TADA.Target.ResultMeasure.MeasureUnitCode",
"ResultMeasure.MeasureUnitCode",
"Conversion.Factor",
"Conversion.Coefficient",
"CharUnit"
)))
# Combine, rename conversion columns for clarity, and final select (guarded).
tada.all <- tada.targets |>
dplyr::full_join(tada.wqx, by = names(tada.targets)) |>
dplyr::rename(
TADA.WQXUnitConversionFactor = Conversion.Factor,
TADA.WQXUnitConversionCoefficient = Conversion.Coefficient
) |>
dplyr::select(dplyr::any_of(c(
"TADA.CharacteristicName",
"ResultMeasure.MeasureUnitCode", # optional column (unprefixed)
"TADA.ResultMeasure.MeasureUnitCode", # canonical column (prefixed)
"TADA.Target.ResultMeasure.MeasureUnitCode",
"TADA.WQXUnitConversionFactor",
"TADA.WQXUnitConversionCoefficient",
"CharUnit"
)))
rm(tada.targets, tada.wqx)
# Identify characteristics with multiple target units (inform user).
mult.target.chars <- tada.all |>
dplyr::select(
TADA.CharacteristicName,
TADA.Target.ResultMeasure.MeasureUnitCode
) |>
dplyr::distinct() |>
dplyr::group_by(TADA.CharacteristicName) |>
dplyr::mutate(
NConvert = length(unique(TADA.Target.ResultMeasure.MeasureUnitCode))
) |>
dplyr::ungroup() |>
dplyr::filter(NConvert > 1)
if (nrow(mult.target.chars) > 1) {
mult.target.list <- mult.target.chars |>
dplyr::group_by(TADA.CharacteristicName) |>
dplyr::mutate(
MultUnits = paste(
unique(TADA.Target.ResultMeasure.MeasureUnitCode),
collapse = ", "
),
MultUnits = stringi::stri_replace_last(
MultUnits,
replacement = " and ",
fixed = ", "
),
MultUnits = paste(
TADA.CharacteristicName,
" (",
MultUnits,
")",
sep = ""
)
) |>
dplyr::ungroup() |>
dplyr::select(
-TADA.Target.ResultMeasure.MeasureUnitCode,
-TADA.CharacteristicName
) |>
dplyr::distinct() |>
dplyr::mutate(CharList = paste(MultUnits, collapse = "; ")) |>
dplyr::select(CharList) |>
dplyr::distinct() |>
stringi::stri_replace_last(replacement = " and ", fixed = "; ")
if (message == TRUE) {
message(
"TADA.CreateUnitRef: The following characteristics have more than one listed target unit: ",
mult.target.list,
". This may be due to units of different types that cannot be converted to match each other. You may wish to review the output of TADA.CreateUnitRef and edit it.",
sep = ""
)
rm(mult.target.list)
}
}
rm(mult.target.chars)
# Drop intermediate column, deduplicate, and return.
tada.all <- tada.all |>
dplyr::select(dplyr::any_of(setdiff(names(tada.all), "CharUnit"))) |>
dplyr::distinct()
return(tada.all)
}
#' Transform Units to TADA Target Units, WQX Target Units or User Specified Units
#'
#' This function converts result and detection limit measure values and units in the
#' input dataframe to TADA target units. It also automatically wrangles common
#' USGS units which include speciation in the unit value, such as "mg/l as N"
#' and "mg/l asNO3", by transferring the speciation information to the
#' TADA.MethodSpeciationName field. No speciation conversions occur in this
#' function.
#'
#' The function uses the "TADA.ResultMeasureValue"
#' and TADA.ResultMeasure.MeasureUnitCode" fields from an autocleaned input
#' dataframe to perform conversions when transform = TRUE.
#'
#' Speciation in USGS result units
#' (ex: "mg/L as N") are addressed in this function by creating additional rows to
#' accommodate all possible combinations from the input TADA dataframe, including
#' those with speciation in units.
#'
#' @param .data TADA dataframe
#'
#' @param transform Boolean argument with two possible values, “TRUE” and “FALSE”.
#' Default is transform = TRUE. When transform = TRUE, result values and units,
#' and detection quantitation limit value and units are converted to TADA target units.
#' This function changes the values within "TADA.ResultMeasure.MeasureUnitCode" and
#' "TADA.DetectionQuantitationLimitMeasure.MeasureValue" to the TADA target units
#' and converts respective values within the "TADA.ResultMeasureValue" and
#' "TADA.DetectionQuantitationLimitMeasure.MeasureValue" fields. When
#' "TADA.ResultMeasure.MeasureUnitCode" is NA, the unit is taken from
#' "TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode" if it not NA. This
#' facilitates estimation of censored data later in the workflow.
#'
#' When transform = FALSE, result values and units, and detection quantitation limit
#' values are units are NOT converted to TADA target units,but columns are appended
#' to indicate what the target units and conversion factors are, and if the data can
#' be converted. This function adds the following four fields ONLY when transform =
#' FALSE: "TADA.WQXUnitConversionFactor", "TADA.Target.ResultMeasure.MeasureUnitCode",
#' "TADA.SpeciationUnitConversion", and "TADA.WQXResultUnitConversion.
#'
#' @param ref Optional character argument in which a user can specify a dataframe
#' by name. Dataframe must contain the columns CharacteristicName, Unit, and TargetUnit.
#' TADA_CreateUnitRef() can be used to help create this dataframe. There are two
#' options that do not require the user to supply a dataframe, "tada" and "wqx".
#' When ref = "wqx" all unit conversion will be based on the WQX unit reference
#' which applies targets at the unit level.
#' When ref = "tada" all unit conversion will be based on TADA priority characteristic
#' units (where applicable) which applies targets at the characteristic level,
#' with any other units assigned by WQX unit reference (at the unit level).
#' The default is ref = "tada".
#'
#' @return A TADA dataframe. Depending on the arguments entered by the user, the
#' number of columns returned may differ. When transform = TRUE, TADA.ResultMeasureValue
#' and TADA.ResultMeasure.MeasureUnitCode are converted to target units. When transform =
#' FALSE, "TADA.WQXUnitConversionFactor", "TADA.Target.ResultMeasure.MeasureUnitCode",
#' "TADA.SpeciationUnitConversion" are added. With either transform argument,
#' "TADA.WQXResultUnitConversion" is added. It indicates if data can be converted.
#' "NoResultValue" means data cannot be converted because there is no
#' ResultMeasureValue, and "NoTargetUnit"means data cannot be converted because
#' the original unit is not associated with a target unit. "Convert" means the data
#' can be transformed.
#'
#' @export
#'
#' @examples
#' # Load example dataset:
#' utils::data(Data_Nutrients_UT)
#'
#' # Do not convert result values and units, but add four new columns titled
#' # "TADA.WQXUnitConversionFactor", "TADA.WQXUnitConversionCoefficient",
#' # "TADA.Target.ResultMeasure.MeasureUnitCode", and
#' # "TADA.SpeciationUnitConversion":
#' ResultUnitsNotConverted <- TADA_ConvertResultUnits(Data_Nutrients_UT,
#' transform = FALSE
#' )
#'
#' # Convert values and units for results and detection limits:
#' ResultUnitsConverted <- TADA_ConvertResultUnits(Data_Nutrients_UT,
#' transform = TRUE
#' )
#'
TADA_ConvertResultUnits <- function(.data, ref = "tada", transform = TRUE) {
# check .data is data.frame
TADA_CheckType(.data, "data.frame", "Input object")
# check transform is boolean
TADA_CheckType(transform, "logical")
# check .data has all of the required columns
if ("TADA.CharacteristicName" %in% colnames(.data)) {
.data <- .data
} else {
# create uppercase version of original CharacteristicName
.data$TADA.CharacteristicName <- toupper(.data$CharacteristicName)
}
if ("TADA.ActivityMediaName" %in% colnames(.data)) {
.data <- .data
} else {
# create uppercase version of original ActivityMediaName
.data$TADA.ActivityMediaName <- toupper(.data$ActivityMediaName)
}
if ("TADA.MethodSpeciationName" %in% colnames(.data)) {
.data <- .data
} else {
# create uppercase version of original MethodSpeciationName
.data$TADA.MethodSpeciationName <- toupper(.data$MethodSpeciationName)
}
if ("TADA.ResultSampleFractionText" %in% colnames(.data)) {
.data <- .data
} else {
# create uppercase version of original ResultSampleFractionText
.data$TADA.ResultSampleFractionText <- toupper(
.data$ResultSampleFractionText
)
}
if ("TADA.ResultMeasureValue" %in% colnames(.data)) {
.data <- .data
} else {
# run TADA_ConvertSpecialChars function
.data <- TADA_ConvertSpecialChars(.data, "ResultMeasureValue")
}
if ("TADA.ResultMeasure.MeasureUnitCode" %in% colnames(.data)) {
.data <- .data
} else {
# create uppercase version of original ResultMeasure.MeasureUnitCode
.data$TADA.ResultMeasure.MeasureUnitCode <- toupper(
.data$ResultMeasure.MeasureUnitCode
)
}
if (
"TADA.DetectionQuantitationLimitMeasure.MeasureValue" %in% colnames(.data)
) {
.data <- .data
} else {
# run TADA_ConvertSpecialChars function
.data <- TADA_ConvertSpecialChars(
.data,
"DetectionQuantitationLimitMeasure.MeasureValue"
)
}
if (
"TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode" %in%
colnames(.data)
) {
.data <- .data
} else {
# create uppercase version of original DetectionQuantitationLimitMeasure.MeasureUnitCode
.data$TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode <- toupper(
.data$DetectionQuantitationLimitMeasure.MeasureUnitCode
)
}
expected_cols <- c(
"TADA.CharacteristicName",
"TADA.ActivityMediaName",
"TADA.MethodSpeciationName",
"TADA.ResultSampleFractionText",
"TADA.ResultMeasureValue",
"TADA.ResultMeasure.MeasureUnitCode",
"TADA.DetectionQuantitationLimitMeasure.MeasureValue",
"TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode"
)
TADA_CheckColumns(.data, expected_cols)
# list of conversion columns
conversion.cols <- c(
"TADA.SpeciationUnitConversion",
"TADA.WQXUnitConversionFactor",
"TADA.WQXUnitConversionCoefficient",
"TADA.Target.MethodSpeciationName",
"TADA.Target.ResultMeasure.MeasureUnitCode"
)
# execute function after checks are passed
# import USGS ref for method speciation
usgs.ref <- TADA_GetUSGSSynonymRef()
usgs.spec <- usgs.ref |>
dplyr::rename(
ResultMeasure.MeasureUnitCode = Code,
TADA.Target.MethodSpeciationName = Target.Speciation,
TADA.WQXUnitConversionFactor = Conversion.Factor
) |>
dplyr::mutate(
ResultMeasure.MeasureUnitCode.Upper = toupper(
ResultMeasure.MeasureUnitCode
),
TADA.Target.MethodSpeciationName = toupper(
TADA.Target.MethodSpeciationName
)
) |>
dplyr::select(
ResultMeasure.MeasureUnitCode,
TADA.Target.MethodSpeciationName
)
usgs.unit <- usgs.ref |>
dplyr::select(Code, CodeNoSpeciation) |>
dplyr::mutate(
TADA.ResultMeasure.MeasureUnitCode = toupper(Code),
CodeNoSpeciation = toupper(CodeNoSpeciation)
) |>
dplyr::select(-Code) |>
dplyr::rename(MeasureUnitCode.match = CodeNoSpeciation)
# separate USGS results with method speciation in units
usgs.results <- .data |>
dplyr::filter(
ResultMeasure.MeasureUnitCode %in% usgs.spec$ResultMeasure.MeasureUnitCode
)
if (dim(usgs.results)[1] == 0) {
# remove intermediate objects
rm(usgs.ref, usgs.spec, usgs.unit)
}
# create df of all results without method speciation in units
other.results <- .data |> dplyr::anti_join(usgs.results, by = colnames(.data))
# internal functions
# internal function to join unit.ref to data
joinUnitRef <- function(
.data,
ref,
convert.col = conversion.cols,
spec = FALSE
) {
# ref join
ref.join <- c(
"TADA.CharacteristicName",
"ResultMeasure.MeasureUnitCode",
"TADA.ResultMeasure.MeasureUnitCode"
)
# add method speciation to ref join if needed
if (spec == TRUE) {
ref.join <- append(ref.join, "TADA.MethodSpeciationName")
}
# join unit ref to data
.data <- .data |>
# remove existing conversion columns
dplyr::select(-tidyselect::any_of(c(conversion.cols))) |>
# add new conversion columns
dplyr::left_join(ref, by = c(ref.join), relationship = "many-to-many")
}
# internal function add TADA.WQXResultUnitConversion flag column
addConversionCol <- function(.data) {
.data <- .data |>
dplyr::mutate(
TADA.WQXResultUnitConversion = dplyr::case_when(
(!is.na(TADA.ResultMeasureValue) &
!is.na(TADA.Target.ResultMeasure.MeasureUnitCode)) ~ as.character(
"Convert"
),
is.na(TADA.ResultMeasureValue) ~ as.character("No Result Value"),
is.na(TADA.Target.ResultMeasure.MeasureUnitCode) ~ as.character(
"No Target Unit"
)
)
)
}
# internal function to create usgs unit ref from main unit ref if needed
if (dim(usgs.results)[1] > 0) {
createUSGSUnitRef <- function(.data, ref, spec) {
meth.spec.usgs <- .data |>
dplyr::select(
ResultMeasure.MeasureUnitCode,
TADA.MethodSpeciationName
) |>
dplyr::distinct()
unit.ref.usgs <- ref |>
dplyr::filter(
ResultMeasure.MeasureUnitCode %in%
usgs.spec$ResultMeasure.MeasureUnitCode
) |>
dplyr::left_join(
spec,
by = dplyr::join_by(ResultMeasure.MeasureUnitCode)
) |>
dplyr::left_join(
meth.spec.usgs,
by = dplyr::join_by(ResultMeasure.MeasureUnitCode)
) |>
dplyr::distinct()
rm(meth.spec.usgs)
return(unit.ref.usgs)
}
}
# if user supplied unit reference was provided
if (is.data.frame(ref)) {
# required columns
expected_ref_cols <- c(
"TADA.CharacteristicName",
"TADA.ResultMeasure.MeasureUnitCode",
"TADA.Target.ResultMeasure.MeasureUnitCode",
"TADA.WQXUnitConversionFactor",
"TADA.WQXUnitConversionCoefficient"
)
if (all(expected_ref_cols %in% colnames(ref)) == FALSE) {
stop(
"The reference dataframe does not contain all fields required for TADA_ConvertResultUnits. Use TADA_CreateUnitRef with the TADA dataframe to create an editable unit reference table with all required columns."
)
if (all(expected_ref_cols %in% colnames(ref)) == TRUE) {
message(
"The reference dataframe contains all fields required for TADA_ConvertResultUnits."
)
}
}
# remove any duplicates in user supplied ref
unit.ref <- ref |> dplyr::distinct()
# create usgs specific ref if any results have method speciation in result units
if (dim(usgs.results)[1] > 0) {
unit.ref.usgs <- createUSGSUnitRef(
usgs.results,
ref = unit.ref,
spec = usgs.spec
)
}
# create message to inform users if user-supplied unit reference contains all combinations present in TADA dataframe
# create list of unique characteristic and unit combinations in data
tada.list <- TADA_CreateUnitRef(.data) |>
dplyr::select(
TADA.CharacteristicName,
TADA.ResultMeasure.MeasureUnitCode
) |>
dplyr::distinct()
# create list of unique characteristic and unit combinations in user-supplied unit ref
user.list <- unit.ref |>
dplyr::select(
TADA.CharacteristicName,
TADA.ResultMeasure.MeasureUnitCode
) |>
dplyr::distinct()
# compare the unique characteristic/unit combinations in data nd unit ref
compare.ref <- tada.list |>
dplyr::anti_join(
user.list,
by = c("TADA.CharacteristicName", "TADA.ResultMeasure.MeasureUnitCode")
)
# if no difference between the two, message that all combinations are present in unit ref
if (nrow(compare.ref) == 0) {
message(
"All CharacteristicName/Unit combinations in the TADA dataframe are represented in user-supplied unit reference."
)
# if there are characteristic/unit combinations in the data that are not in the unit ref, print a warning message listing them
} else {
compare.list <- compare.ref |>
dplyr::mutate(
Comb = paste(CharacteristicName, " (", Code, ")", sep = "")
) |>
dplyr::mutate(CombList = paste(Comb, collapse = ", ")) |>
dplyr::select(CombList) |>
dplyr::distinct() |>
stringi::stri_replace_last(fixed = ",", " and")
message(paste(
"TADA_ConvertResultUnits: The following CharacteristicName and ResultMeasure.MeasureUnitCode combinations are not included in the user-supplied unit reference dataframe: ",
compare.list,
". Consider revising the user-supplied unit reference dataframe and running TADA_ConvertResultUnits again.",
sep = ""
))
rm(compare.list)
}
# remove intermediate objects
rm(compare.ref, tada.list, user.list)
}
# if user did not provide a dataframe
if (!is.data.frame(ref)) {
# if no unit reference df was provided by user or user input was "tada"
if (ref == "tada") {
unit.ref <- TADA_CreateUnitRef(.data, message = FALSE)
unit.ref <- unit.ref |> dplyr::distinct()
if (dim(usgs.results)[1] > 0) {
unit.ref.usgs <- createUSGSUnitRef(
usgs.results,
ref = unit.ref,
spec = usgs.spec
)
}
}
if (ref == "wqx") {
# import WQX unit ref
wqx.ref <- TADA_GetMeasureUnitRef()
wqx.ref <- wqx.ref |>
dplyr::mutate(
Target.Unit = toupper(Target.Unit),
Code = toupper(Code)
) |>
dplyr::rename(
MeasureUnitCode.match = Code,
TADA.Target.ResultMeasure.MeasureUnitCode = Target.Unit,
TADA.WQXUnitConversionFactor = Conversion.Factor,
TADA.WQXUnitConversionCoefficient = Conversion.Coefficient
) |>
dplyr::select(
MeasureUnitCode.match,
TADA.Target.ResultMeasure.MeasureUnitCode,
TADA.WQXUnitConversionFactor,
TADA.WQXUnitConversionCoefficient
) |>
dplyr::distinct()
# create unit ref
unit.ref <- TADA_UniqueCharUnitSpeciation(.data) |>
dplyr::left_join(
usgs.unit,
by = dplyr::join_by(TADA.ResultMeasure.MeasureUnitCode)
) |>
dplyr::mutate(
MeasureUnitCode.match = ifelse(
is.na(MeasureUnitCode.match),
TADA.ResultMeasure.MeasureUnitCode,
MeasureUnitCode.match
)
) |>
dplyr::left_join(wqx.ref, by = dplyr::join_by(MeasureUnitCode.match)) |>
dplyr::select(-MeasureUnitCode.match) |>
dplyr::distinct()
if (dim(usgs.results)[1] > 0) {
unit.ref.usgs <- createUSGSUnitRef(
usgs.results,
ref = unit.ref,
spec = usgs.spec
)
}
rm(wqx.ref)
}
}
# internal function to set other.results or usgs.results as null if not included in df
setNull <- function(df.name) {
if (dim(df.name)[1] == 0) {
df.name <- NULL
}
return(df.name)
}
# join unit.ref for data without speciation in units
if (dim(other.results)[1] > 0) {
other.data <- joinUnitRef(other.results, ref = unit.ref, spec = FALSE)
# add TADA.WQXResultUnitConversion flag column for data without speciation in units
other.data <- addConversionCol(other.data)
}
# set other.results to NULL if no results
if (dim(other.results)[1] == 0) {
other.data <- setNull(other.results)
}
if (dim(usgs.results)[1] > 0) {
# join unit.ref for usgs data with speciation in units
usgs.data <- joinUnitRef(usgs.results, ref = unit.ref.usgs, spec = TRUE)
# add TADA.WQXResultUnitConversion flag column for data without speciation in units
usgs.data <- addConversionCol(usgs.data)
# add target method speciation name when needed
usgs.data <- usgs.data |>
dplyr::mutate(
TADA.MethodSpeciationName = ifelse(
!is.na(TADA.Target.MethodSpeciationName),
TADA.Target.MethodSpeciationName,
toupper(TADA.MethodSpeciationName)
),
# replace UNKNOWN or NONE method speciation name with NA
TADA.MethodSpeciationName = ifelse(
TADA.MethodSpeciationName %in% c("UNKNOWN", "NONE"),
NA,
TADA.MethodSpeciationName
),
TADA.MethodSpeciationName = as.character(TADA.MethodSpeciationName)
)
# remove intermediat objects
rm(unit.ref.usgs, usgs.spec, usgs.unit)
}
# set other.results to NULL if no results
if (dim(usgs.results)[1] == 0) {
usgs.data <- setNull(usgs.results)
}
# remove intermediate objects
rm(usgs.results, other.results)
# internal function to combine usgs and other data
joinUSGSOther <- function(usgs.data = NULL, other.data = NULL) {
# create clean data set by combining or assigning df
if (!is.null(usgs.data) & !is.null(other.data) == TRUE) {
clean.data <- other.data |>
dplyr::full_join(usgs.data, by = colnames(other.data))
}
if (!is.null(usgs.data) == TRUE & !is.null(other.data) == FALSE) {
clean.data <- usgs.data
}
if (!is.null(usgs.data) == FALSE & !is.null(other.data) == TRUE) {
clean.data <- other.data
}
rm(other.data, usgs.data)
return(clean.data)
}
if (transform == FALSE) {
message(
"TADA_ConvertResultUnits: When Transform = FALSE, result values and units are NOT converted. Conversions are required for many other TADA functions to work properly (such as result value range checks)."
)
# join usgs and other data
final.data <- joinUSGSOther(
usgs.data = usgs.data,
other.data = other.data
) |>
# reorder columns
TADA_OrderCols() |>
# update col order
TADA_CreateComparableID()
rm(usgs.data, other.data)
}
if (transform == TRUE) {
if (!is.null(usgs.data)) {
message(paste0(
"NOTE: Dataset contains ",
dim(usgs.data)[1],
" USGS results with speciation information in both the result unit and method speciation columns. This function overwrites the TADA method speciation column with the speciation provided in the result unit column."
))
# add target method speciation name when needed
usgs.data <- usgs.data |>
dplyr::mutate(
TADA.MethodSpeciationName = ifelse(
!is.na(TADA.Target.MethodSpeciationName),
TADA.Target.MethodSpeciationName,
toupper(TADA.MethodSpeciationName)
),
# replace UNKNOWN or NONE method speciation name with NA
TADA.MethodSpeciationName = ifelse(
TADA.MethodSpeciationName %in% c("UNKNOWN", "NONE"),
NA,
TADA.MethodSpeciationName
)
)
}
clean.data <- joinUSGSOther(usgs.data = usgs.data, other.data = other.data)
rm(usgs.data, other.data)
# Transform result measure value to Target Unit only if target unit exists
clean.data <- clean.data |>
# apply conversions where there is a target unit, use original value if no target unit
dplyr::mutate(
TADA.ResultMeasureValue = dplyr::case_when(
is.na(TADA.ResultMeasureValue) ~ TADA.ResultMeasureValue,
!is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ ((TADA.ResultMeasureValue + TADA.WQXUnitConversionCoefficient) *
TADA.WQXUnitConversionFactor),
is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.ResultMeasureValue
)
)
# populate TADA.ResultMeasure.MeasureUnitCode
clean.data <- clean.data |>
# use target unit where there is a target unit, use original unit if no target unit
dplyr::mutate(
TADA.ResultMeasure.MeasureUnitCode = dplyr::case_when(
!is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.Target.ResultMeasure.MeasureUnitCode,
is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.ResultMeasure.MeasureUnitCode
)
)
# create detection unit ref
det.ref <- unit.ref |>
dplyr::ungroup() |>
dplyr::rename(
DetectionQuantitationLimitMeasure.MeasureUnitCode = ResultMeasure.MeasureUnitCode,
TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode = TADA.ResultMeasure.MeasureUnitCode
) |>
dplyr::distinct()
det.join <- c(
"TADA.CharacteristicName",
"DetectionQuantitationLimitMeasure.MeasureUnitCode",
"TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode"
)
# Transform TADA.DetectionQuantitationLimitMeasure.MeasureValue value to target value only if target unit exists
det.data <- clean.data |>
dplyr::select(-tidyselect::any_of(conversion.cols)) |>
dplyr::left_join(det.ref, by = det.join) |>
# apply conversions where there is a target unit, use original value if no target unit
dplyr::mutate(
TADA.DetectionQuantitationLimitMeasure.MeasureValue = dplyr::case_when(
is.na(
TADA.DetectionQuantitationLimitMeasure.MeasureValue
) ~ TADA.DetectionQuantitationLimitMeasure.MeasureValue,
!is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ ((TADA.DetectionQuantitationLimitMeasure.MeasureValue +
TADA.WQXUnitConversionCoefficient) *
TADA.WQXUnitConversionFactor),
is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.DetectionQuantitationLimitMeasure.MeasureValue
)
)
# populate TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode
final.data <- det.data |>
# use target unit where there is a target unit, use original unit if no target unit
dplyr::mutate(
TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode = dplyr::case_when(
!is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.Target.ResultMeasure.MeasureUnitCode,
is.na(
TADA.Target.ResultMeasure.MeasureUnitCode
) ~ TADA.DetectionQuantitationLimitMeasure.MeasureUnitCode
)
) |>
# Remove unneccessary conversion columns
dplyr::select(-tidyselect::any_of(conversion.cols)) |>
# update ID and column ordering
TADA_CreateComparableID() |>
TADA_OrderCols()
rm(clean.data, det.data, det.ref)
}
# remove remaining intermediate objects if they exist
rm(unit.ref)
return(final.data)
}
#' Convert Depth Units
#'
#' The **TADA_ConvertDepthUnits** function converts depth units to a consistent
#' unit. Depth values and units are most commonly associated with lake
#' data, and are populated in the *ActivityDepthHeightMeasure*,
#' *ActivityTopDepthHeightMeasure*, *ActivityBottomDepthHeightMeasure*, and
#' *ResultDepthHeightMeasure* Result Value/Unit columns.
#'