/
process.R
2067 lines (1741 loc) · 70.4 KB
/
process.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
#' Configure AusTraits database object
#'
#' Creates the config object which gets passed onto `dataset_process`. The config list contains
#' the subset of definitions and unit conversions for those traits for a each study.
#' `dataset_configure` is used in the `remake::make` process to configure individual studies mapping the
#' individual traits found in that study along with any relevant unit conversions
#' and definitions. `dataset_configure` and `dataset_process` are applied to every study
#' in the `remake.yml` file.
#'
#' @param filename_metadata Metadata yaml file for a given study
#' @param definitions Definitions read in from the `traits.yml`
#'
#' @return List with `dataset_id`, `metadata`, `definitions` and `unit_conversion_functions`
#' @importFrom purrr map_chr
#' @importFrom dplyr filter
#' @importFrom rlang .data
#' @importFrom lubridate dmy
#' @export
#'
#' @examples
#' \dontrun{
#' dataset_configure("data/Falster_2003/metadata.yml", read_yaml("config/traits.yml"))
#' }
dataset_configure <- function(
filename_metadata,
definitions) {
dataset_id <- basename(dirname(filename_metadata))
# Read metadata
metadata <- read_metadata(filename_metadata)
# Table of trait_mapping
trait_mapping <-
metadata[["traits"]] %>%
util_list_to_df2() %>%
dplyr::filter(!is.na(.data$trait_name))
# Subset of definitions
definitions <-
definitions$elements[names(definitions$elements) %in% trait_mapping$trait_name]
list(dataset_id = dataset_id,
metadata = metadata,
definitions = definitions)
}
#' Load Dataset
#'
#' `dataset_process` is used to load individual studies using the config file generated
#' from `dataset_configure()`. `dataset_configure` and `dataset_process` are applied to every
#' study in the `remake.yml` file.
#'
#' @param filename_data_raw Raw `data.csv` file for any given study
#' @param config_for_dataset Config settings generated from `dataset_configure()`
#' @param schema Schema for traits.build
#' @param resource_metadata Metadata about the traits compilation read in from the config folder
#' @param unit_conversion_functions `unit_conversion.csv` file read in from the config folder
#' @param filter_missing_values Default filters missing values from the excluded data table;
#' change to false to see the rows with missing values
#'
#' @return List, AusTraits database object
#' @export
#' @importFrom dplyr select mutate filter arrange distinct full_join everything any_of
#' @importFrom tidyr spread
#' @importFrom purrr reduce map_chr
#' @importFrom rlang .data
#'
#' @examples
#' \dontrun{
#' dataset_process("data/Falster_2003/data.csv", dataset_configure("data/Falster_2003/metadata.yml",
#' read_yaml("config/traits.yml")),
#' get_schema(),
#' get_schema("config/metadata.yml", "metadata"),
#' get_unit_conversions("config/unit_conversions.csv"))
#' }
dataset_process <- function(filename_data_raw,
config_for_dataset,
schema,
resource_metadata,
unit_conversion_functions,
filter_missing_values = TRUE) {
dataset_id <- config_for_dataset$dataset_id
metadata <- config_for_dataset$metadata
definitions <- config_for_dataset$definitions
# Load and clean trait data
traits <-
readr::read_csv(filename_data_raw, col_types = cols(), guess_max = 100000, progress = FALSE) %>%
process_custom_code(metadata[["dataset"]][["custom_R_code"]])()
# Load and process contextual data
contexts <-
metadata$contexts %>%
process_format_contexts(dataset_id, traits)
# Load and clean trait data
traits <-
traits %>%
process_parse_data(dataset_id, metadata, contexts, schema)
# Context ids needed to continue processing
context_ids <- traits$context_ids
# Extract location data from metadata
locations <-
metadata$locations %>%
process_format_locations(dataset_id, schema)
traits <-
traits$traits %>%
process_add_all_columns(
c(names(schema[["austraits"]][["elements"]][["traits"]][["elements"]]),
"parsing_id", "location_name", "taxonomic_resolution", "methods", "unit_in")
)
# Replace old `location_id` with a new `location_id`
if (nrow(locations) > 0) {
traits <-
traits %>%
dplyr::select(-dplyr::all_of(c("location_id"))) %>%
dplyr::left_join(
by = c("location_name"),
locations %>% dplyr::select(dplyr::all_of(c("location_name", "location_id"))) %>% dplyr::distinct()
)
traits <-
traits %>%
dplyr::mutate(
location_id = ifelse(.data$entity_type == "species", NA_character_, .data$location_id)
)
}
# Where missing, fill variables in traits table with values from locations
# Trait metadata should probably have precedence -- right now trait metadata
# is being read in during `process_parse_data` and getting overwritten here #TODO
if (nrow(locations) > 0) {
vars <- c("basis_of_record", "life_stage", "collection_date",
"measurement_remarks", "entity_type")
for (v in vars) {
# Merge into traits from location level
if (v %in% unique(locations$location_property)) {
traits_tmp <- traits %>%
dplyr::left_join(
by = "location_id",
locations %>%
tidyr::pivot_wider(names_from = "location_property", values_from = "value") %>%
dplyr::mutate(col_tmp = .data[[v]]) %>%
dplyr::select(dplyr::any_of(c("location_id", "col_tmp"))) %>%
stats::na.omit()
)
# Use location level value if present
traits[[v]] <- ifelse(!is.na(traits_tmp[["col_tmp"]]), traits_tmp[["col_tmp"]], traits[[v]])
}
}
# Remove any values included to map into traits table
locations <- locations %>% dplyr::filter(!(.data$location_property %in% vars))
}
traits <- traits %>%
process_flag_unsupported_traits(definitions) %>%
process_flag_excluded_observations(metadata) %>%
process_flag_unsupported_characters() %>%
process_flag_unsupported_values(definitions) %>%
process_convert_units(definitions, unit_conversion_functions) %>%
process_flag_out_of_range_values(definitions) %>%
process_create_observation_id(metadata) %>%
process_taxonomic_updates(metadata) %>%
# Sorting of data
dplyr::mutate(
# For cells with multiple values (separated by a space), sort these alphabetically
value = ifelse(is.na(.data$error), util_separate_and_sort(.data$value), .data$value),
value_type = factor(.data$value_type, levels = names(schema$value_type$values))
) %>%
dplyr::arrange(.data$observation_id, .data$trait_name, .data$value_type) %>%
# Ensure everything converted to character type
util_df_convert_character()
# Record contributors
contributors <-
metadata$contributors %>%
process_format_contributors(dataset_id, schema)
# Record sources
sources <- metadata$source %>% lapply(util_list_to_bib) %>% purrr::reduce(c)
# Record methods
methods <- process_format_methods(metadata, dataset_id, sources, contributors)
# Retrieve taxonomic details for known species
taxonomic_updates <-
traits %>%
dplyr::select(
dplyr::all_of(
c("dataset_id", "original_name", aligned_name = "taxon_name",
taxonomic_resolution = "taxonomic_resolution"))
) %>%
dplyr::distinct() %>%
dplyr::arrange(.data$aligned_name)
# Taxon names explicitly excluded in metadata also excluded from taxonomic updates table
if (!is.na(metadata[["exclude_observations"]][1])) {
taxa_to_exclude <-
metadata[["exclude_observations"]] %>%
traits.build::util_list_to_df2() %>%
dplyr::mutate(
find = stringr::str_split(.data$find, ", ")
) %>%
tidyr::unnest_longer("find") %>%
dplyr::filter(.data$variable == "taxon_name")
tmp <- taxa_to_exclude$find %>% process_standardise_names()
taxonomic_updates <-
taxonomic_updates %>%
dplyr::filter(!.data$aligned_name %in% tmp)
}
## A temporary dataframe created to generate and bind `method_id`,
## for instances where the same trait is measured twice using different methods
# Test ABRS_2023
tmp_bind <-
metadata[["traits"]] %>%
process_generate_method_ids()
# Ensure correct order of columns in traits table
# At this point, need to retain `taxonomic_resolution`, because taxa table & taxonomic_updates not yet assembled
traits <-
traits %>%
# Need to remove blank column to bind in real one; blank exists because `method_id` in schema
dplyr::select(-"method_id") %>%
dplyr::left_join(
by = c("trait_name", "methods"),
tmp_bind
) %>%
dplyr::select(
dplyr::all_of(c(names(schema[["austraits"]][["elements"]][["traits"]][["elements"]]),
"error", "taxonomic_resolution", "unit_in"))
)
# Remove missing values is specified
if (filter_missing_values == TRUE) {
traits <-
traits %>% dplyr::filter(!(!is.na(.data$error) & (.data$error == "Missing value")))
}
# Update metadata
metadata <- resource_metadata
if (is.null(metadata[["related_identifiers"]][1])) {
metadata[["related_identifiers"]] <- list()
}
metadata[["related_identifiers"]] <-
util_append_to_list(
metadata[["related_identifiers"]],
list(
related_identifier_type = "url",
identifier = "https://github.com/traitecoevo/traits.build",
relation_type = "isCompiledBy",
resource_type = "software",
version = as.character(utils::packageVersion("traits.build"))
)
)
# Combine for final output
ret <-
list(
traits = traits %>% dplyr::filter(is.na(.data$error)) %>% dplyr::select(-dplyr::all_of(c("error", "unit_in"))),
locations = locations,
contexts = context_ids$contexts %>% dplyr::select(-dplyr::any_of(c("var_in"))),
methods = methods,
excluded_data = traits %>%
dplyr::filter(!is.na(.data$error)) %>%
dplyr::select(dplyr::all_of(c("error")), everything()) %>%
dplyr::select(-dplyr::all_of(c("unit_in"))),
taxonomic_updates = taxonomic_updates %>%
dplyr::filter(.data$aligned_name %in% traits$taxon_name),
taxa = taxonomic_updates %>%
dplyr::select(dplyr::all_of(c(taxon_name = "aligned_name"))) %>%
dplyr::distinct(),
contributors = contributors,
sources = sources,
definitions = definitions,
schema = schema,
metadata = metadata,
build_info = list(session_info = utils::sessionInfo())
)
class(ret) <- c("list", "traits.build")
ret
}
#' Build dataset
#'
#' Build specified dataset. This function completes three steps, which can be executed separately if desired:
#' `dataset_configure`, `dataset_process`, `dataset_update_taxonomy`
#'
#' @param filename_metadata Metadata yaml file for a given study
#' @param filename_data_raw Raw `data.csv` file for any given study
#' @param definitions Definitions read in from the `traits.yml`
#' @param unit_conversion_functions `unit_conversion.csv` file read in from the config folder
#' @param schema Schema for traits.build
#' @param resource_metadata metadata for the compilation
#' @param taxon_list Taxon list
#' @param filter_missing_values Default filters missing values from the excluded data table;
#' change to false to see the rows with missing values
#' @return List, AusTraits database object
#' @export
#'
#' @examples
#' \dontrun{
#' dataset_build(
#' "data/Falster_2003/data.csv",
#' "data/Falster_2003/metadata.yml",
#' read_yaml("config/traits.yml"),
#' get_unit_conversions("config/unit_conversions.csv"),
#' get_schema(),
#' get_schema("config/metadata.yml", "metadata"),
#' read_csv_char("config/taxon_list.csv")
#' )
#' }
dataset_build <- function(
filename_metadata,
filename_data_raw,
definitions,
unit_conversion_functions,
schema,
resource_metadata,
taxon_list,
filter_missing_values = TRUE) {
dataset_config <- dataset_configure(filename_metadata, definitions)
dataset_raw <- dataset_process(
filename_data_raw, dataset_config, schema, resource_metadata, unit_conversion_functions,
filter_missing_values = filter_missing_values)
dataset <- dataset_update_taxonomy(dataset_raw, taxon_list)
dataset
}
#' Apply custom data manipulations
#'
#' Applies custom data manipulations if the metadata field `custom_R_code` is not empty
#' Otherwise no manipulations will be done by applying the `identity` function.
#' The code `custom_R_code` assumes a single input.
#'
#' @param txt Character text within custom_R_code of a `metadata.yml` file
#'
#' @return character text containing custom_R_code if custom_R_code is not empty,
#' otherwise no changes are made
process_custom_code <- function(txt) {
if (!is.null(txt) && !is.na(txt) && nchar(txt) > 0) {
txt2 <-
# Trim white space, quotes, new line from front and back
txt %>% stringi::stri_trim_both("[^'\"\\ \\n]", negate = FALSE) %>%
# Squish internal white space, also removes new line characters
stringr::str_replace_all("\\s+", " ")
# test: txt <-" '' \n Total of 23.5 bitcoins. "
function(data) {
envir <- new.env()
# Read in extra functions used in custom R code
if (file.exists("R/custom_R_code.R")) {
source("R/custom_R_code.R", local = envir)
}
eval(parse(text = txt2), envir = envir)
}
} else {
identity
}
}
#' Create entity id
#'
#' Creates 3-part entity id codes that combine a segment for species, population,
#' and, when applicable, individual.
#' This depends upon a `parsing_id` being established when the `data.csv` file is first read in.
#'
#' @param data The traits table at the point where this function is called
#' @param metadata Yaml file with metadata
#'
#' @return Character string
process_create_observation_id <- function(data, metadata) {
# Create four IDs: `population_id`, `individual_id`, `observation_id`, `repeat_measurements_id`
# Create `population_id`
# `population_id`'s are numbers assigned to unique combinations of
# location_name, treatment_context_id and plot_context_id
# Their purpose is to allow `population_level` measurements to be
# easily mapped to individuals within the given population
if (
!all(is.na(data[["location_name"]])) ||
!all(is.na(data[["plot_context_id"]])) ||
!all(is.na(data[["treatment_context_id"]]))
) {
data <- data %>%
dplyr::mutate(
population_id = paste(.data$location_name, .data$plot_context_id, .data$treatment_context_id, sep = "")
)
} else {
data <- data %>%
dplyr::mutate(
population_id = NA_character_
)
}
data <- data %>%
dplyr::mutate(
pop_id_segment = ifelse(
(!is.na(.data$location_name) |
!is.na(.data$treatment_context_id) |
!is.na(.data$plot_context_id)) &
.data$entity_type %in% c("individual", "population", "metapopulation"),
process_generate_id(.data$population_id, ""),
NA),
pop_id_segment = ifelse(
is.na(.data$pop_id_segment) & .data$entity_type %in% c("individual", "population", "metapopulation"),
"pop_unk",
.data$pop_id_segment),
population_id = .data$pop_id_segment
)
## Create `individual_id`
# For datasets where there are individual-level measurements
# (i.e. entity_type = `individual`), the `parsing_id` values
# that were created in the `process_parse_data` function are
# `individual_id`s.
# There are 3 circumstances:
# 1. There is an `individual_id` column read in through metadata$data
# and `parsing_id` is equivalent to `individual_id`.
# 2. There is only a single observation for each individual,
# and therefore `parsing_id` values assigned based upon row number
# correctly identifies an individual. This includes instances where
# there is a `temporal context`, but different individuals were
# measured each time.
# 3. There are multiple observations for each individual, but these are
# presented in the `data.csv` file as multiple columns and therefore
# row number correctly identifies an individual.
# For datasets where an `individual_id` is not assigned via metadata$dataset
if (all(is.na(data[["individual_id"]]))) {
# Check which rows of data include individual-level measurements
# (based on entity type)
has_ind_value <-
data %>%
dplyr::filter(!is.na(.data$value)) %>%
dplyr::group_by(.data$parsing_id) %>%
dplyr::summarise(check_for_ind = any(stringr::str_detect(.data$entity_type, "individual"))) %>%
dplyr::ungroup()
# If yes, `individual_id` is copied from `parsing_id`
# If no, `individual_id` is set to NA
# This step is required so that for the final `individual_id`
# only rows of data containing some individual-level data are numbered,
# to avoid missing numbers in the `individual_id` sequence
data <-
data %>%
dplyr::left_join(has_ind_value, by = "parsing_id") %>%
dplyr::mutate(individual_id = ifelse(.data$check_for_ind == TRUE, .data$parsing_id, NA))
# For datasets where an `individual_id` is assigned via metadata$dataset
} else {
# Replace NAs in `individual_id` column with `parsing_id`
data <-
data %>%
dplyr::mutate(
individual_id = ifelse(
is.na(.data$individual_id) & .data$entity_type == "individual",
.data$parsing_id, .data$individual_id
))
}
# Create final `individual_id` within each species and population
# (as identified by their segment numbers)
# The function `process_generate_id` ensures that values with the same
# `parsing_id`/`individual_id` are given the same value
data <-
data %>%
dplyr::group_by(.data$taxon_name, .data$population_id) %>%
dplyr::mutate(
ind_id_segment = ifelse(
!is.na(.data$individual_id) & .data$entity_type == "individual",
process_generate_id(.data$individual_id, ""),
NA),
ind_id_segment = ifelse(
is.na(.data$ind_id_segment) & is.na(.data$entity_type),
process_generate_id(.data$individual_id, "entity_unk"),
.data$ind_id_segment)
) %>%
dplyr::ungroup() %>%
dplyr::mutate(individual_id = .data$ind_id_segment, check_for_ind = NA)
## Create `observation_id` for a single set of trait measurements made on an entity
# (where an entity can be an individual, population, or taxon)
i <- !is.na(data$value)
data[i, ] <-
data[i, ] %>%
dplyr::group_by(.data$dataset_id) %>%
dplyr::mutate(
observation_id =
paste(.data$taxon_name, .data$population_id, .data$individual_id, .data$temporal_context_id,
.data$entity_type, .data$life_stage, .data$source_id, .data$entity_context_id,
.data$basis_of_record, .data$collection_date, .data$original_name, sep = "-") %>%
process_generate_id("", sort = TRUE)
) %>%
dplyr::ungroup()
## Create repeat_measurements_id for datasets where there are multiple measurements per observation,
# such as response curve data (where an entity can be an individual, population, or taxon)
if (!is.null(metadata[["dataset"]][["repeat_measurements_id"]])) {
if (metadata[["dataset"]][["repeat_measurements_id"]] == TRUE) {
i <- !is.na(data$value)
data$repeat_measurements_id <- data$repeat_measurements_id %>% as.character()
data[i, ] <-
data[i, ] %>%
dplyr::group_by(
.data$dataset_id, .data$observation_id, .data$trait_name, .data$value_type,
.data$method_id, .data$method_context_id
) %>%
dplyr::mutate(
repeat_measurements_id = dplyr::row_number() %>% process_generate_id("")
) %>%
dplyr::ungroup()
}
}
traits_table <- metadata[["traits"]] %>% util_list_to_df2()
if (!is.null(traits_table[["repeat_measurements_id"]])) {
to_add_id <- traits_table %>%
dplyr::filter(.data$repeat_measurements_id == TRUE) %>%
dplyr::pull(.data$trait_name)
i <- !is.na(data$value) & data$trait_name %in% to_add_id &
# To ensure `repeat_measurements_id`'s are only added to data where `repeat_measurements_id`
# was specified as TRUE in the traits table (applicable to when a trait is entered twice,
# one TRUE and one FALSE):
(!is.na(data$repeat_measurements_id) & data$repeat_measurements_id == TRUE)
data[i, ] <-
data[i, ] %>%
dplyr::group_by(
.data$dataset_id, .data$observation_id, .data$trait_name, .data$value_type,
.data$method_id, .data$method_context_id
) %>%
dplyr::mutate(
repeat_measurements_id = dplyr::row_number() %>% process_generate_id("")
) %>%
dplyr::ungroup()
}
data %>% dplyr::select(-dplyr::all_of(c("check_for_ind")))
}
#' Function to generate sequence of integer ids from vector of names
#' Determines number of 00s needed based on number of records
#' @param x Vector of text to convert
#' @param prefix Text to put before id integer
#' @param sort Logical to indicate whether x should be sorted before ids are generated
#' @return Vector of ids
process_generate_id <- function(x, prefix, sort = FALSE) {
make_id_segment <- function(n, prefix) {
sprintf(paste0("%s%0", max(2, ceiling(log10(n))), "d"), prefix, seq_len(n))
}
d <- x %>%
unique() %>%
subset(., !is.na(.))
if (sort) d <- sort(d, na.last = TRUE)
id <- make_id_segment(length(d), prefix)
id[match(x, d)]
}
#' Function to generate sequence of integer ids for methods
#' @param metadata_traits the traits section of the metadata
#' @return Tibble with traits, methods, and method_id
#' @importFrom rlang .data
process_generate_method_ids <- function(metadata_traits) {
metadata_traits %>%
util_list_to_df2() %>%
dplyr::filter(!is.na(.data$trait_name)) %>%
dplyr::select(dplyr::all_of(c("trait_name", "methods"))) %>%
dplyr::distinct() %>%
# Group by traits to generate ids
# This handles instances where multiple methods used for a single trait within a dataset
dplyr::group_by(.data$trait_name) %>%
dplyr::mutate(method_id = process_generate_id(.data$methods, "")) %>%
dplyr::ungroup()
}
#' Format context data from list to tibble
#'
#' Format context data read in from the `metadata.yml` file. Converts from list to tibble.
#'
#' @param my_list List of input information
#' @param dataset_id Identifier for a particular study in the AusTraits database
#' @param traits Table of trait data (for this function, just the data.csv file with custom_R_code applied)
#' @return Tibble with context details if available
#' @importFrom rlang .data
#'
#' @examples
#' \dontrun{
#' process_format_contexts(read_metadata("data/Apgaua_2017/metadata.yml")$context, dataset_id, traits)
#' }
process_format_contexts <- function(my_list, dataset_id, traits) {
process_content_worker <- function(x, id, traits) {
vars <- c(
"dataset_id", "context_property", "category", "var_in",
"find", "value", "description"
)
out <-
tibble::tibble(
context_property = x$context_property,
category = x$category,
var_in = x$var_in,
util_list_to_df2(x$values)
) %>%
dplyr::mutate(dataset_id = dataset_id) %>%
dplyr::select(dplyr::any_of(vars))
## If the field `description` is missing from metadata[["contexts"]] for the specific
# context property, create a column now
if (!"description" %in% names(out)) {
out[["description"]] <- NA_character_
}
## If the fields `find` and `value` are both missing from metadata[["contexts"]] for
# the specific context property create them
## They are both the unique set of values in the column in the data.csv file
if (all(!c("find", "value") %in% names(out))) {
out <- out %>%
# The following line shouldn't be needed, as we tested this was missing for the if statement above
dplyr::select(-any_of(c("value"))) %>%
dplyr::left_join(
by = "var_in",
tibble::tibble(
var_in = out[["var_in"]][1],
value = unique(traits[[out$var_in[1]]])
) %>%
dplyr::filter(!is.na(.data$value))
) %>%
dplyr::mutate(find = .data$value)
}
if ("find" %in% names(out)) {
out <- out %>%
dplyr::mutate(find = ifelse(is.na(.data$find), .data$value, .data$find))
} else {
out <- out %>%
dplyr::mutate(find = .data$value)
}
# Ensure character types
out %>%
dplyr::mutate(dplyr::across(dplyr::all_of(c("find", "value")), as.character))
}
if (!is.na(my_list[1])) {
contexts <-
my_list %>%
purrr::map_df(process_content_worker, dataset_id, traits)
} else {
contexts <-
tibble::tibble(dataset_id = character(), var_in = character())
}
contexts
}
process_create_context_ids <- function(data, contexts) {
# Select context_cols
tmp <- contexts %>%
dplyr::select(dplyr::all_of(c("context_property", "var_in"))) %>%
dplyr::distinct()
# Extract context columns
context_cols <- data %>%
dplyr::select(dplyr::any_of(tmp$var_in)) %>%
dplyr::mutate(dplyr::across(everything(), as.character))
names(context_cols) <- tmp$context_property
# Find and replace values for each context property
for (v in unique(contexts$context_property)) {
## First filter to each property
xx <- contexts %>%
dplyr::filter(.data$context_property == v)
## Create named vector
xxx <- stats::setNames(xx$value, xx$find)
## Use named vector for find and value
context_cols[[v]] <- xxx[context_cols[[v]]]
}
# `group_by` category and create ids
tmp <-
contexts %>%
dplyr::select(dplyr::all_of(c("context_property", "category", "value"))) %>%
dplyr::distinct()
categories <-
c("plot_context", "treatment_context", "entity_context",
"temporal_context", "method_context") %>%
subset(., . %in% tmp$category)
ids <- dplyr::tibble(.rows = nrow(context_cols))
id_link <- list()
for (w in categories) {
xx <- contexts %>%
dplyr::filter(.data$category == w)
vars <- unique(xx[["context_property"]])
make_id <- function(x) {
sprintf(paste0("%0", max(2, ceiling(log10(x)), na.rm = TRUE), "d"), x)
}
# Below, unite function turns NAs into text, we need to convert back
# Need to modify structure of NA, depending on the number of
# variables in vars so two NAs will be NA_NA
# only treat rows where everything is NA as NA
NAs <- paste(rep("NA", length(vars)), collapse = "_")
xxx <-
context_cols %>%
dplyr::select(dplyr::all_of(vars)) %>%
tidyr::unite("combined", remove = FALSE) %>%
dplyr::mutate(
combined = ifelse(.data$combined == NAs, NA, .data$combined),
id = ifelse(!is.na(.data$combined), .data$combined %>%
as.factor() %>% as.integer() %>% make_id(), NA)
) %>%
dplyr::select(-dplyr::all_of(c("combined")))
## Store ids
ids[[paste0(w, "_id")]] <- xxx[["id"]]
## Create link values
for (v in vars) {
id_link[[v]] <-
xxx %>%
dplyr::rename(dplyr::all_of(c("value" = v))) %>%
dplyr::select(dplyr::all_of(c("value", "id"))) %>%
dplyr::filter(!is.na(.data$id)) %>%
dplyr::distinct() %>%
util_df_convert_character() %>%
dplyr::group_by(.data$value) %>%
dplyr::summarise(
context_property = v,
category = w,
link_id = paste0(w, "_id"),
link_vals = paste(.data$id, collapse = ", ")
)
}
}
contexts_finished <-
contexts %>%
dplyr::filter(!is.na(.data$value)) %>%
dplyr::left_join(
id_link %>% dplyr::bind_rows(),
by = c("context_property", "category", "value")
) %>%
dplyr::distinct(dplyr::across(-dplyr::any_of("find")))
list(
contexts = contexts_finished %>% util_df_convert_character(),
ids = ids %>% util_df_convert_character()
)
}
#' Format location data from list to tibble
#'
#' Format location data read in from the `metadata.yml` file. Converts from list to tibble.
#'
#' @param my_list List of input information
#' @param dataset_id Identifier for a particular study in the AusTraits database
#' @param schema Schema for traits.build
#'
#' @return Tibble with location details if available
#' @importFrom rlang .data
#' @importFrom dplyr select mutate filter arrange distinct case_when full_join everything any_of bind_cols
#'
#' @examples
#' \dontrun{
#' process_format_locations(read_metadata("data/Falster_2003/metadata.yml")$locations, "Falster_2003")
#' }
process_format_locations <- function(my_list, dataset_id, schema) {
# Default, if length 1 then it's an "na"
if (length(unlist(my_list)) == 1) {
empty_locations <- tibble::tibble() %>%
process_add_all_columns(
names(schema[["austraits"]][["elements"]][["locations"]][["elements"]]),
add_error_column = FALSE
)
return(empty_locations)
}
out <-
my_list %>%
lapply(lapply, as.character) %>%
purrr::map_df(util_list_to_df1, .id = "name") %>%
dplyr::mutate(dataset_id = dataset_id) %>%
dplyr::rename(dplyr::all_of(c("location_property" = "key", "location_name" = "name"))) %>%
process_add_all_columns(
names(schema[["austraits"]][["elements"]][["locations"]][["elements"]]),
add_error_column = FALSE
) %>%
dplyr::group_by(.data$dataset_id) %>%
dplyr::mutate(
location_id = process_generate_id(.data$location_name, "", sort = TRUE)
) %>%
dplyr::ungroup() %>%
# Reorder so type, description come first, if present
dplyr::mutate(
i = dplyr::case_when(
.data$location_property == "description" ~ 1,
.data$location_property == "latitude (deg)" ~ 2,
.data$location_property == "longitude (deg)" ~ 3,
TRUE ~ 4)
) %>%
dplyr::arrange(.data$location_id, .data$location_name, .data$i, .data$location_property) %>%
dplyr::select(-dplyr::all_of(c("i")))
out
}
#' Flag any unrecognised traits
#'
#' Flag any unrecognised traits, as defined in the `traits.yml` file.
#'
#' @param data Tibble or dataframe containing the study data
#' @param definitions Definitions read in from the `traits.yml` file in the config folder
#'
#' @importFrom rlang .data
#' @return Tibble with unrecognised traits flagged in the "error" column
process_flag_unsupported_traits <- function(data, definitions) {
# Create error column if not already present
# Necessary for this function and not the other `process_flag_...` functions as
# this is run first during `dataset_process()`
if (is.null(data[["error"]]))
data[["error"]] <- NA_character_
# Exclude traits not in definitions
i <- data$trait_name %in% names(definitions)
data %>%
dplyr::mutate(error = ifelse(!i, "Trait name not in trait dictionary", .data$error))
}
#' Flag any excluded observations
#'
#' Checks the metadata yaml file for any excluded observations. If there are none,
#' returns the original data. If there are excluded observations returns the mutated data
#' with excluded observations flagged in a new column.
#'
#' @param data Tibble or dataframe containing the study data
#' @param metadata Yaml file with metadata
#'
#' @importFrom stringr str_squish
#' @importFrom rlang .data
#' @return Dataframe with flagged excluded observations if there are any
process_flag_excluded_observations <- function(data, metadata) {
if (length(metadata$exclude_observations) == 1 && is.na(metadata$exclude_observations)) return(data)
fix <-
metadata$exclude_observations %>%
util_list_to_df2() %>%
tidyr::separate_longer_delim("find", delim = ", ") %>%
dplyr::mutate(find = str_squish(.data$find))
if (nrow(fix) == 0) return(data)
fix <- split(fix, fix$variable)
traits <- metadata$traits %>% util_list_to_df2
for (v in names(fix))
if (v %in% traits$trait_name) {
data <- data %>%
dplyr::mutate(
error = ifelse(
.data$trait_name == v & .data$value %in% fix[[v]]$find,
"Observation excluded in metadata",
.data$error))
} else {
data <- data %>%
dplyr::mutate(
error = ifelse(
.data[[v]] %in% fix[[v]]$find,
"Observation excluded in metadata",
.data$error))
}
data
}
#' Check values in a vector do not contain disallowed characters
#'
#' `util_check_disallowed_chars` checks if values in a vector do not contain disallowed characters,
#' i.e. values outside of ASCII.
#'
#' @param object Vector
#'
#' @return Vector of logical values
util_check_disallowed_chars <- function(object) {
f <- function(x) {
i <- charToRaw(x)
# Allow all ascii text
is_ascii <- i < 0x7F
!(is_ascii)
}
disallowed <- object %>% lapply(f)
disallowed %>% lapply(any) %>% unlist()
}
#' Flag values with unsupported characters
#'
#' Disallowed characters are flagged as errors, including for numeric traits, prior to
#' unit conversions to avoid their conversion to NAs during the unit conversion process.
#'
#' @param data Tibble or dataframe containing the study data
#'
#' @importFrom rlang .data
#' @return Tibble with flagged values containing unsupported characters
process_flag_unsupported_characters <- function(data) {
data <- data %>%
dplyr::mutate(
error = ifelse(is.na(.data$error) & util_check_disallowed_chars(.data$value),
"Value contains unsupported characters", .data$error)
)
data
}
#' Check values in one vector against values in another vector
#'
#' `util_check_all_values_in` checks if values in vector x are in y. Values in x may
#' contain multiple values separated by `sep` so these are split first using `str_split`.
#'
#' @param x Vector
#' @param y Vector