-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDefineAndUpdateVariables.R
1612 lines (1366 loc) · 54.3 KB
/
DefineAndUpdateVariables.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
# The general function for redefining StoxData:
RedefineData <- function(
StoxData, RawData,
Redefinition = data.table::data.table(),
StoxDataFormat = c("Biotic", "Acoustic"),
NumberOfCores = 1L
) {
StoxDataFormat <- match_arg_informative(StoxDataFormat)
# Add the requested variable:
StoxData <- AddToStoxData(
StoxData = StoxData,
RawData = RawData,
VariableNames = Redefinition$ReplaceBy,
NumberOfCores = NumberOfCores,
StoxDataFormat = StoxDataFormat
)
# Remove the old:
lapply(StoxData, replaceAndDelete, VariableReplacement = Redefinition)
return(StoxData)
}
# Function to replace the existing column by the new, as stored in the VariableReplacement:
replaceAndDelete <- function(table, VariableReplacement) {
presentVariableName <- which(VariableReplacement$VariableName %in% names(table))
hasReplaceBy <- VariableReplacement$ReplaceBy %in% names(table)
if(length(presentVariableName) && hasReplaceBy) {
# Delete the present column:
table[, (VariableReplacement[presentVariableName, VariableName]) := NULL]
# ... and then rename the new to the old name:
setnames(table, VariableReplacement[presentVariableName, ReplaceBy], VariableReplacement[presentVariableName, VariableName])
}
}
##################################################
#' Redefine StoxBioticData variables by data from BioticData
#'
#' This function redefines one or more columns of \code{\link{StoxBioticData}} by columns of \code{\link{BioticData}}.
#'
#' @param StoxBioticData An input of \link{ModelData} object
#' @param BioticData An input of \link{ModelData} object
#' @param Redefinition A table of the columns "VariableName", representing the variable to redefine; and "ReplaceBy", representing the variable from BioticData to replace by.
#'
#' @return
#' A \code{\link{StoxBioticData}} object.
#'
#' @export
#'
RedefineStoxBiotic <- function(
StoxBioticData, BioticData,
Redefinition = data.table::data.table()
) {
# Redefine StoxBioticData:
RedefineData(
StoxData = StoxBioticData, RawData = BioticData,
Redefinition = Redefinition,
StoxDataFormat = "Biotic"
)
}
##################################################
#' Define translation
#'
#' This function defines the translation table used as input to \code{\link{TranslateStoxBiotic}} and similar functions to translate values of one or more columns to new values given by a table or read from a CSV file.
#'
#' @inheritParams general_arguments
#' @param VariableName The name of the variable to translate. This will be the name of the first column of the TranslationTable when generated from the StoX GUI.
#' @param Conditional Logical: If TRUE condition the translation on values of other variables.
#' @param ConditionalVariableNames The names of the variables to condition the translation on. Must be given if \code{Conditional == TRUE}. This will be the name(s) of the third column and onwards of the TranslationTable when generated from the StoX GUI.
#' @param DefinitionMethod Character: A string naming the method to use, one of "ResourceFile", for reading the table from the file given by \code{FileName}; and "Table", for defining the \code{TranslationTable} directly as an input.
#' @param FileName The csv file holding a table with the \code{TranslationTable}. Required columns are given by \code{ValueColumn} and \code{NewValueColumn}, and, in the case that Conditional == TRUE, \code{ConditionalValueColumns}.
#' @param ValueColumn,NewValueColumn The name of the columns of \code{FileName} representing the current values and the values to translate to, respectively.
#' @param ConditionalValueColumns The names of the columns of \code{FileName} representing the conditional values.
#' @param TranslationTable A table holding the following columns: The first column holds the values to translate FROM, the second column holds the values to translate TO, and the remaining zero or more columns holds the values for the conditional variables specified in \code{ConditionalVariableNames}. I.e., if \code{VariableName} = "IndividualAge" and \code{ConditionalVariableNames} = "IndividualSex", and the \code{TranslationTable} has values 3, 4 and "F" in the first row, female fish at age 3 are translated to age 4. Use NA to translate missing values (shown as "-" in Preview in the StoX GUI, and usually as empty cell in excel). Values in the \code{TranslationTable} can be given either as single values or as expressions of functions of the variable specified by the column name. See details of \code{\link{DefineTranslation}}.
#'
#' @details The columns of the \code{TranslationTable} (except the NewValue column) can be given in one of two ways: (1) A single value or a string to be evaluated and matched using the "\%in\%" operator, such as "HER" or "c(\"HER\", \"CLU\")"; or (2) a string expressing a function of the variable given by the column name, such as "function(IndividualTotalLength) IndividualTotalLength > 10". When the \code{TranslationnTable} is given in the StoX GUI the strings need not be escaped ((1) HER or c("HER", "CLU"); or (2) function(IndividualTotalLength) IndividualTotalLength > 10).
#'
#' E.g., to set all individuals with missing IndividualMaturity as "Adult" if longer than 10 cm, use \code{function(IndividualMaturity) is.na(IndividualMaturity)} in the first column named "IndividualMaturity", \code{Adult} in the "NewValue" column, and \code{function(IndividualTotalLength) IndividualTotalLength > 10} in the third (conditional) column named "IndividualTotalLength". To translate all IndividualMaturity to a e.g. NA, use \code{function(IndividualMaturity) TRUE} in the "IndividualMaturity" column and \code{NA} in the "NewValue" column.
#'
#' @return
#' A \code{\link{Translation}} object.
#'
#' @seealso \code{\link{TranslateStoxBiotic}}, \code{\link{TranslateStoxAcoustic}}, \code{\link{TranslateBiotic}}, \code{\link{TranslateAcoustic}}, \code{\link{TranslateStoxLanding}}, \code{\link{TranslateLanding}}, \code{\link{TranslateICESBiotic}} and \code{\link{TranslateICESAcoustic}} for applying the translation.
#'
#' @export
#'
DefineTranslation <- function(
processData, UseProcessData = FALSE,
DefinitionMethod = c("ResourceFile", "Table"),
FileName = character(),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
ValueColumn = character(),
NewValueColumn = character(),
ConditionalValueColumns = character()
) {
# Return immediately if UseProcessData = TRUE:
if(UseProcessData) {
return(processData)
}
DefinitionMethod <- match_arg_informative(DefinitionMethod)
if(DefinitionMethod == "ResourceFile") {
# Get the conversion table:
Translation <- readVariableTranslation(
FileName = FileName,
VariableName = VariableName,
ValueColumn = ValueColumn,
NewValueColumn = NewValueColumn,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
ConditionalValueColumns = ConditionalValueColumns,
UseProcessData = UseProcessData
)
}
else if(DefinitionMethod == "Table"){
Translation <- TranslationTable
}
else {
stop("Invalid DefinitionMethod")
}
# We need VariableName:
if(!length(VariableName)) {
warning("VariableName must be given.")
}
relevantColumns <- c(
VariableName,
"NewValue"
)
# Append the conditional variables:
if(Conditional) {
if(length(ConditionalVariableNames)) {
relevantColumns <- append(relevantColumns, ConditionalVariableNames)
}
else {
warning("ConditionalVariableNames should be given if Conditional == TRUE.")
}
}
Translation <- Translation[, ..relevantColumns]
# Sanitize the table:
sanitizeExpression(Translation)
return(Translation)
}
# Function for reading a conversion table:
readVariableTranslation <- function(FileName, VariableName, ValueColumn, NewValueColumn, Conditional, ConditionalVariableNames, ConditionalValueColumns, UseProcessData = FALSE) {
# Read the file:
tanslation <- data.table::fread(FileName, encoding = "UTF-8", colClasses = "character")
if(!length(ValueColumn) || !nchar(ValueColumn)) {
stop("ValueColumn must be given as the name of the column giving the values to be translated.")
}
else {
if(! ValueColumn %in% names(tanslation)) {
stop("The ValueColumn (", ValueColumn, ") must be in the file ", FileName, ". Available column names are ", paste(names(tanslation), collapse = ", "), " .")
}
}
if(!length(NewValueColumn) || !nchar(NewValueColumn)) {
stop("NewValueColumn must be given as the name of the column giving the values to be translated to.")
}
else {
if(! NewValueColumn %in% names(tanslation)) {
stop("The NewValueColumn (", NewValueColumn, ") must be in the file ", FileName, ". Available column names are ", paste(names(tanslation), collapse = ", "), " .")
}
}
# Get the Value and NewValue:
tanslation[, eval(VariableName) := get(ValueColumn)]
tanslation[, NewValue := get(NewValueColumn)]
if(Conditional) {
if(!length(ConditionalValueColumns) || any(nchar(ConditionalValueColumns) == 0)) {
stop("ConditionalValueColumns must be given as the name of the column giving the values to be translated to.")
}
else {
if(! all(ConditionalValueColumns %in% names(tanslation))) {
stop("All of the ConditionalValueColumns (", paste(NewValueColumn, collapse = ", "), ") must be in the file ", FileName, ".")
}
}
for(ConditionalValueColumn in ConditionalValueColumns) {
tanslation[, eval(ConditionalValueColumn) := get(ConditionalValueColumn)]
}
}
return(tanslation)
}
oldToNewTranslationOne <- function(x) {
# Detect whether the translation is conditional:
conditional <- "ConditionalVariableName" %in% names(x)
if(conditional) {
# We only treat one row at the time, so we do not need to extract the first element of x$VariableName:
out <- data.table::data.table(
# Use the Value as the first column and ConditionalValue as the last, and add the VariableName and ConditionalVariableName afterwards:
x$Value,
NewValue = x$NewValue,
x$ConditionalValue
)
names(out) <- c(x$VariableName, "NewValue", x$ConditionalVariableName)
}
else {
# We only treat one row at the time, so we do not need to extract the first element of x$VariableName:
out <- data.table::data.table(
# Use the Value as the first column, and add the VariableName afterwards:
x$Value,
NewValue = x$NewValue
)
names(out) <- c(x$VariableName, "NewValue")
}
return(out)
}
# Function to convert variables given a conversion table (by reference):
translateVariables <- function(
data,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
Translation,
TranslationTable = data.table::data.table(),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
translate.keys = FALSE,
PreserveClass = TRUE,
warnMissingTranslation = FALSE
) {
# Get the Translation:
TranslationDefinition <- match_arg_informative(TranslationDefinition)
if(TranslationDefinition == "FunctionParameter") {
Translation <- TranslationTable
# Sanitize the table:
sanitizeExpression(Translation)
}
if(!nrow(Translation)) {
return(NULL)
}
# Split the translation table into a list, thus treating only one row at the time. This is probably sloppy coding, but it works:
translationList <- split(Translation, seq_len(nrow(Translation)))
# Check whether the old required columns are present in the translation table, and transform to the new form:
oldRequiredColumns <- getRstoxDataDefinitions("TranslationOldRequiredColumns")
if(all(oldRequiredColumns %in% names(translationList[[1]]))) {
translationList <- lapply(translationList, oldToNewTranslationOne)
}
# Warn if there are columns in the translation that are not present in the data. Check only the first translation, as all translations have the same columns in the new form, and in the old form (that is used by StoxBiotic()) this check is not as important:
someButNotAllPresentOneTable <- function(table, translationList) {
translationNames <- setdiff(names(translationList[[1]]), "NewValue")
any(translationNames %in% names(table)) && !all(translationNames %in% names(table))
}
someButNotAllPresent <- unlist(lapply(
data,
someButNotAllPresentOneTable,
translationList = translationList
))
# Run the conversion for each table of the data:
lapplyToStoxData(
data,
translateOneTable,
translationList = translationList,
translate.keys = translate.keys,
PreserveClass = PreserveClass,
warnMissingTranslation = warnMissingTranslation
)
}
# Function to translate one table:
translateOneTable <- function(table, translationList, translate.keys = FALSE, PreserveClass = TRUE, warnMissingTranslation = FALSE) {
# If the variable to translate is present in the table, check whether the conditional variables are present in the table:
variableToTranslate <- sapply(translationList, function(x) names(x)[1])
variableToTranslateIsPresent <- variableToTranslate %in% names(table)
# Abort if the variableToTranslate are not present in the table:
if(!any(variableToTranslateIsPresent)) {
# This return value is currently not used:
return(FALSE)
}
# List the conditional variables and check whether those linked to the variables present in the table are also present:
conditionalVariables <- sapply(translationList, function(x) names(x)[-c(1, 2)])
conditionalVariablesNotPresentInTable <- setdiff(unlist(conditionalVariables[variableToTranslateIsPresent]), names(table))
if(length(conditionalVariablesNotPresentInTable)) {
warning("StoX: The following conditional variables are not present in the table: ", paste(conditionalVariablesNotPresentInTable, collapse = ", "), ".")
}
# Apply the translation, one line at the time:
matches <- lapply(
translationList,
translateOneTranslationOneTable,
table = table,
translate.keys = translate.keys,
PreserveClass = PreserveClass,
warnMissingTranslation = warnMissingTranslation
)
# Change the type after matching and before translating to avoid type conversion warnings:
if(!PreserveClass) {
for(ind in seq_along(translationList)) {
variableToTranslate <- names(translationList[[ind]])[1]
newClass <- class(translationList[[ind]]$NewValue)
setColumnClasses(table, structure(list(newClass), names = variableToTranslate))
}
}
# Replace. This assumes that there is exactly one row in each element of the translationList:
for(ind in seq_along(matches)) {
if(length(matches[[ind]])) {
variableToTranslate <- names(translationList[[ind]])[1]
replacement <- translationList[[ind]]$NewValue
# Compare classes, and change class of the replacement of different to capture the warning but avoid data.table warning "Coercing --- RHS to --- to match the type of column..."
variableToTranslate_class <- class(table[[variableToTranslate]])
replacement_class <- class(replacement)
replacement_original <- replacement
suppressWarnings(class(replacement) <- variableToTranslate_class)
if(is.na(replacement) && !is.na(replacement_original)) {
warning("StoX: The class of the NewValue of the translation table (", replacement_class, ": ", replacement_original, ") does not match the class of the ", variableToTranslate, " (", variableToTranslate_class, "). Missing value (NA) introduced.")
}
table[matches[[ind]], eval(variableToTranslate) := ..replacement]
}
}
return(TRUE)
}
getMissingCombinations <- function(translation, table, variableKeys) {
# Get the names of those columns in the data:
transNames <- translation[, ..variableKeys]
variablesInTable <- unname(unlist(transNames[1,]))
if(!all(variablesInTable %in% names(table))) {
return(NULL)
}
tab <- table[, ..variablesInTable]
# And the names of columns holding the values of those variables in the translation:
valueVariablesInTranslation <- intersect(c("ConditionalValue", "Value"), names(translation))
trans <- translation[, ..valueVariablesInTranslation]
names(trans) <- variablesInTable
# Match the type of the table:
matchClass(trans, tab)
# Then simply set diff those values from those in the data, and unniquify:
missingCombinations <- tab[!trans, on = variablesInTable]
missingCombinations <- data.table::setorderv(unique(missingCombinations), variablesInTable)
return(missingCombinations)
}
getMissingCombinationsWarning <- function(x) {
c(
paste(names(x), collapse = ", "),
x[, do.call(paste, c(.SD, list(sep = ", ")))],
""
)
}
matchClass <- function(A, B) {
for (x in colnames(A)) {
A[, eval(x) := eval( call( paste0("as.", class(B[[x]])), get(x) ))]
}
}
# Function to apply to all tables of the input data, converting the variables:
translateOneTranslationOneTable <- function(translationListOne, table, translate.keys = FALSE, PreserveClass = TRUE, warnMissingTranslation = FALSE) {
# Check that the table contains the variable to translate:
if(names(translationListOne)[1] %in% names(table)) {
## Check for values of the data that are not covered by the translation:
#notPresentInTranslation <- sort(
# setdiff(
# table[[Translation$VariableName[1]]],
# Translation$Value
# )
#)
if(warnMissingTranslation) {
# Get the combinations of ConditionalVariableNames and VariableName missing in the Translation:
variableKeys <- setdiff(names(translationListOne), "NewValue")
missingCombinations <- getMissingCombinations(translationListOne, table = table, variableKeys = variableKeys)
if(nrow(missingCombinations)) {
warnMessage <- c(
"StoX: The following values are present in the data but not in the translation, and were not translated: ",
getMissingCombinationsWarning(missingCombinations)
)
warnMessage <- paste(warnMessage, collapse = "\n")
warning(warnMessage)
}
}
}
variableToTranslate <- names(translationListOne)[1]
# Do nothing if the variable is a key:
isKeys <- endsWith(variableToTranslate, "Key")
if(!translate.keys && isKeys) {
warning("StoX: The variable ", variableToTranslate, " is a key and cannot be modified ")
}
else {
# Convert the class to the class of the existing value in the table:
if(PreserveClass) {
# Convert the class of the translationList to that of the variable to transate:
translationListOneConverted <- convertTranslationListClass(
translationList = translationListOne,
table = table
)
# Check whether the NewValue has changed, and if it has changed to NA, report a warning:
if(!identical(translationListOneConverted, translationListOne)) {
atNAAndDiffering <- is.na(translationListOne) & !is.na(translationListOneConverted)
if(any(atNAAndDiffering)) {
warning("StoX: NAs introduced when converting class of the columns ", paste(names(translationListOne)[atNAAndDiffering], collapse = ", "), ", to the class of the corresponding column of the data. To prevent converting class of the translation to the class of the data, use PreserveClass = FALSE.")
}
translationListOne <- translationListOneConverted
}
}
# Replace by the new value:
if(variableToTranslate %in% names(table)) {
varsToMatch <- setdiff(names(translationListOne), "NewValue")
matches <- lapply(varsToMatch, matchVariable, list = translationListOne, table = table)
# Any empty matches indicate that the variable of interest is not present, and triggers a warning and no match:
emptyMatches <- lengths(matches) == 0
if(any(emptyMatches)) {
#warning("StoX: The following variables are used in the translation but are not present in the table. This results in no translation: ", paste(varsToMatch[emptyMatches], collapse = ", "), ".")
matches[emptyMatches] <- rep(list(FALSE), sum(emptyMatches))
}
matches <- apply(do.call(cbind, matches), 1, all)
return(matches)
}
}
return(NULL)
}
# Function to match a condition given in the element 'variableName' of 'list' to the corresponding element in 'table', either as an evaluable function expression string, or an evaluable string:
matchVariable <- function(variableName, list, table) {
# Special case for NA:
if(is.na(list[[variableName]]) || identical(list[[variableName]], "NA")) {
is.na(table[[variableName]])
}
# Check whether the translation key is a function string to be evaluated:
else if(isFunctionString(list[[variableName]], variableName)) {
# Evaluate the function:
eval(parse(text = list[[variableName]]))(table[[variableName]])
}
# Otherwise check whether the table column is in the evaluated string:
else {
vector <- eval(parse(text = deparse(list[[variableName]])))
if(!is.list(vector) && is.vector(vector) && length(dim(vector)) < 2) {
table[[variableName]] %in% vector
}
else {
stop("Expressions given in the TranslationTable can either be functions given as strings, og expressions which when evaluated result in a one dimensional non-list vectors.")
}
}
}
# Test if a value is a function string:
isFunctionString <- function(x, variableName) {
if(is.character(x)) {
functionPrefix <- paste0("function(", variableName, ")")
xWithoutWhitespace <- gsub("[[:space:]]", "", x)
startsWith(xWithoutWhitespace, functionPrefix)
}
else {
FALSE
}
}
convertTranslationListClass <- function(translationList, table) {
variableToTanslate <- names(translationList)[1]
if(NROW(table) && variableToTanslate %in% names(table)) {
# Convert class of NewValue to that of the corresponding column in the data:
existingClass <- firstClass(table[[variableToTanslate]])
newClass <- firstClass(translationList$NewValue)
if(!identical(existingClass, newClass)) {
if(all(is.na(translationList$NewValue))) {
translationList$NewValue <- getNAByType(existingClass)
}
else {
class(translationList$NewValue) <- existingClass
}
}
}
return(translationList)
}
### # Function to convert the class of list[[element]] to the class of :
### convertClassToExistingOneElement <- function(list, x, element) {
###
### # Convert the NewValue to the class of the existing value:
### if(length(x[[names(list)[1]]])) {
### existingClass <- firstClass(x[[names(list)[1]]])
### newClass <- class(list[[element]])[1]
###
### if(!identical(existingClass, newClass)) {
### if(all(is.na(list[[element]]))) {
### list[[element]] <- getNAByType(existingClass)
### }
### else {
### class(list[[element]]) <- existingClass
### }
### #class(list[[element]]) <- existingClass
### }
### }
###
### return(list)
### }
# Function to apply a function to StoX data, which may be a list of tables or a list of lists of tables:
lapplyToStoxData <- function(x, fun, ...) {
# Check the depth of the list, either with tables at the top level og with lists of tables:
if(is.list(x[[1]]) && !data.table::is.data.table(x[[1]])) {
lapply(x, function(y) lapply(y, fun, ...))
}
else {
lapply(x, fun, ...)
}
}
##################################################
#' Translate StoxBioticData
#'
#' This function translates one or more columns of \code{\link{StoxBioticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @param TranslationDefinition The method to use for defining the Translation, one of \code{FunctionParameter} to define the Translation on the fly in this function using the \code{TranslationTable}, or \code{FunctionInput} to import \code{\link{Translation}} process data from a previously run process using the function \code{\link{DefineTranslation}}. When reading the translation from a file \code{FunctionInput} must be used.
#' @param PreserveClass Logical: If TRUE (the default) do not convert the class of the data by the class of the translation table. E.g., with the default (\code{PreserveClass} = TRUE), if the variable to translate is integer (1, 2, etc) and the NewValue is character ("First", "Second", etc), the NewValue will be converted to integer before translation, resulting in NA if the character strings are not convertible to integer. In this example it could be the user's intention to convert the class of the variable to translate instead, which is possible using \code{PreserveClass} = FALSE.
#'
#' @return
#' A \code{\link{StoxBioticData}} object.
#'
#' @export
#'
TranslateStoxBiotic <- function(
StoxBioticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
StoxBioticDataCopy <- data.table::copy(StoxBioticData)
# Translate StoxBioticData:
translateVariables(
data = StoxBioticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(StoxBioticDataCopy)
}
##################################################
#' Translate StoxAcousticData
#'
#' This function translates one or more columns of \code{\link{StoxAcousticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{StoxAcousticData}} object.
#'
#' @export
#'
TranslateStoxAcoustic <- function(
StoxAcousticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
StoxAcousticDataCopy <- data.table::copy(StoxAcousticData)
translateVariables(
data = StoxAcousticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(StoxAcousticDataCopy)
}
##################################################
#' Translate BioticData
#'
#' This function translates one or more columns of \code{\link{BioticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{BioticData}} object.
#'
#' @export
#'
TranslateBiotic <- function(
BioticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
BioticDataCopy <- data.table::copy(BioticData)
translateVariables(
data = BioticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(BioticDataCopy)
}
##################################################
#' Translate AcousticData
#'
#' This function translates one or more columns of \code{\link{AcousticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{AcousticData}} object.
#'
#' @export
#'
TranslateAcoustic <- function(
AcousticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
AcousticDataCopy <- data.table::copy(AcousticData)
translateVariables(
data = AcousticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(AcousticDataCopy)
}
##################################################
#' Translate StoxLandingData
#'
#' This function translates one or more columns of \code{\link{StoxLandingData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{StoxLandingData}} object.
#'
#' @export
#'
TranslateStoxLanding <- function(
StoxLandingData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
StoxLandingDataCopy <- data.table::copy(StoxLandingData)
translateVariables(
data = StoxLandingDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(StoxLandingDataCopy)
}
##################################################
#' Translate LandingData
#'
#' This function translates one or more columns of \code{\link{LandingData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{LandingData}} object.
#'
#' @export
#'
TranslateLanding <- function(
LandingData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
LandingDataCopy <- data.table::copy(LandingData)
translateVariables(
data = LandingDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(LandingDataCopy)
}
##################################################
#' Translate ICESBioticData
#'
#' This function translates one or more columns of \code{\link{ICESBioticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{ICESBioticData}} object.
#'
#' @export
#'
TranslateICESBiotic <- function(
ICESBioticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
ICESBioticDataCopy <- data.table::copy(ICESBioticData)
translateVariables(
data = ICESBioticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(ICESBioticDataCopy)
}
##################################################
#' Translate ICESAcousticData
#'
#' This function translates one or more columns of \code{\link{ICESAcousticData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{ICESAcousticData}} object.
#'
#' @export
#'
TranslateICESAcoustic <- function(
ICESAcousticData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
ICESAcousticDataCopy <- data.table::copy(ICESAcousticData)
translateVariables(
data = ICESAcousticDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(ICESAcousticDataCopy)
}
##################################################
#' Translate ICESDatrasData
#'
#' This function translates one or more columns of \code{\link{ICESDatrasData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{ICESDatrasData}} object.
#'
#' @export
#'
TranslateICESDatras <- function(
ICESDatrasData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
ICESDatrasDataCopy <- data.table::copy(ICESDatrasData)
translateVariables(
data = ICESDatrasDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,
Translation = Translation,
PreserveClass = PreserveClass
)
return(ICESDatrasDataCopy)
}
##################################################
#' Translate ICESDatsuscData
#'
#' This function translates one or more columns of \code{\link{ICESDatsuscData}} to new values given by the input \code{Translation}.
#'
#' @inheritParams DefineTranslation
#' @inheritParams ModelData
#' @inheritParams ProcessData
#' @inheritParams TranslateStoxBiotic
#'
#' @return
#' A \code{\link{ICESDatsuscData}} object.
#'
#' @export
#'
TranslateICESDatsusc <- function(
ICESDatsuscData,
TranslationDefinition = c("FunctionParameter", "FunctionInput"),
VariableName = character(),
Conditional = FALSE, # If TRUE, adds a column to the parameter format translationTable.
ConditionalVariableNames = character(),
TranslationTable = data.table::data.table(),
Translation,
PreserveClass = TRUE
) {
# Make a copy, as we are translating by reference:
ICESDatsuscDataCopy <- data.table::copy(ICESDatsuscData)
translateVariables(
data = ICESDatsuscDataCopy,
TranslationDefinition = TranslationDefinition,
TranslationTable = TranslationTable,
VariableName = VariableName,
Conditional = Conditional,
ConditionalVariableNames = ConditionalVariableNames,