-
Notifications
You must be signed in to change notification settings - Fork 1
/
create-xmap.Rmd
3149 lines (2702 loc) · 91.1 KB
/
create-xmap.Rmd
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
---
title: "Creating the ``r params$package_name`` R package"
author: "Cynthia Huang"
date: 2022-12-21
output:
litr::litr_html_document:
toc: true
params:
package_name: "xmap" # <-- change this to your package name
package_parent_dir: "." # <-- relative to this file's location
---
```{=html}
<!-- This Rmd file contains all the code needed to define an R package. Press "Knit" in RStudio or more generally run `litr::render("name-of-this-file.Rmd")` to generate the R package. Remember that when you want to modify anything about the R package, you should modify this document rather than the package that is outputted.
-->
```
## Package Setup
### DESCRIPTION file
```{r package-setup, message=FALSE, results='hide'}
usethis::create_package(
path = ".",
fields = list(
Package = params$package_name,
Version = "0.0.1.9004",
Title = "A principled approach to recoding and redistributing data between nomenclature",
Description = "Provides tools for creating and verifying classification, category and/or nomenclature mapping objects.",
`Authors@R` = c(
person(given = "Cynthia", family = "Huang", email = "cynthia@gmail.com", role = c("aut", "cre")),
person(given = "Laura", family = "Puzzello", role = c("aut", "fnd"))
),
`Config/testthat/edition` = 3,
URL = "https://github.com/cynthiahqy/xmap"
)
)
usethis::use_mit_license(copyright_holder = "C. Huang")
```
### Dependencies
```{r dependencies}
# Imports for Validation
usethis::use_package("R", type = "Depends", min_version = "4.1")
usethis::use_package("rlang", min_version = "1.0.0")
usethis::use_package("cli")
# Imports for Construction and verification helpers
usethis::use_package("tibble", min_version = "3.1.0")
usethis::use_package("pillar", min_version = "1.6.0")
usethis::use_package("vctrs", min_version = "0.6.0")
usethis::use_package("tidyr")
usethis::use_package("dplyr")
usethis::use_package("glue", "Imports")
usethis::use_package("tidyselect") ## for free with dplyr
# Suggests for xmap coercion to other classes
usethis::use_package("stats", type = "Suggests")
usethis::use_package("Matrix", type = "Suggests") ## for sparse matrices
# Suggests for Tests and Vignettes
usethis::use_package("ggplot2", type = "Imports")
usethis::use_package("ggraph", type = "Imports")
usethis::use_package("testthat", type = "Suggests")
usethis::use_package("matlib", type = "Suggests")
usethis::use_package("forcats", type = "Suggests")
usethis::use_package("stringr", type = "Suggests")
usethis::use_package("patchwork", type = "Suggests")
usethis::use_package("ggbump", type = "Suggests")
```
### Utilities
```{r}
## retain for interactive
library(rlang)
```
```{r send_to="R/utils.R"}
#' Defaults for NULL values
#' @name op-null-default
#' @keywords internal
`%||%` <- function(x, y) if (is.null(x)) y else x
```
### Package Level Documentation
``` {package-doc}
#' xmap: A principled approach to recoding and redistributing data between nomenclature
#'
#' @description
#' Provides tools for verifying classification, category and/or nomenclature
#' mapping objects such as named vectors or lists, and lookup tables.
#'
#' @keywords internal
#' @import rlang
"_PACKAGE"
```
## Package Design Notes
### Function Types and Naming conventions
This should correspond to `@keywords` and `send_to=` arguments.
#### Data Argument Names
- `x` for ambiguous inputs (e.g. named vector OR named list), or generic methods
- `df` for data frames (e.g. pairs and links)
- `.xmap` for xmap objects, following the [Dot prefix tidyverse design pattern](https://design.tidyverse.org/dots-prefix.html) since `xmap_to` and other fncs will eventually have passthrough `...`
#### Internal Helpers
Errors and Messages:
- `abort_*`: should raise a `cli::cli_abort()` message, and pass through calls.
- See [#59](https://github.com/cynthiahqy/conformr-xmap-project/issues/59) for references on how to construct and format errors.
Properties:
- `.get_<attrs>`: should always retrieve attributes (usually of `xmap_df`)
- `.calc_<property>`: calculates something based on object and/or its attributes (usually of `xmap_df`)
- `vhas_`: takes in vectors, returns boolean
Construction:
- `*_xmap_df()`: class construction functions
- `new_xmap_df()`
- `validate_xmap_df()` -- internal, quick!
- `as_xmap_df()`
#### Data
- `mock_` are input objects:
- `mock$named_`
- `mock$df_`
- `mock$xmap_`
- See [#177](https://github.com/cynthiahqy/conformr-xmap-project/issues/117) for references on documenting datasets
#### Non-`xmap_df` inputs
Candidate Pairs:
- `as_pairs()` to generate crosswalks
- `as_pairs_from_list()`
- `as_pairs_from_named_vector()`
- `add_weights_*` to attach weights and return links
- `verify_named` functions:
- `verify_named_all_pairs` for pairwise checks
- `verify_named_all_names/values` for node set checks
- `verify_named_matchset_names/values_<filter>` for node set element checks
Candidate Links:
- `as_links()`: could be a generic that calls different (internal?) methods and adds/extracts weights like:
- `as_links_from_matrix()`
- `as_links_from_igraph()`
- `verify_links_as_xmap()`, takes tidyselect?
Coerce:
- `as_xmap()` wraps construction functions, takes tidyselect
- `is_xmap()`
#### `xmap_df` inputs
Describe:
- `xmap_has`
- single input variants of `vhas` fncs
- `verify_xmap_as_*` special types of xmaps;
Modify:
- `xmap_<verb>` returns an `xmap_df`
Convert:
- `xmap_to`: returns non-`xmap` outputs
#### ARCHIVED: `xmap` subclasses
- functions specific to subclass end with the `_<subclass>` suffix, and/or named as S3 dispatch method (i.e. `<generic>.<subclass>`). For example `validate_xmap_df()` and `xmap_validate.xmap_df()`
- "internal" construction and validation functions take string arguments for column selection
- user helpers take expression arguments (NSE) for column selection
- functions should probably never end in `_xmap()` because it's not clear which subclass they act on.
For functions accepting `xmap` as inputs:
- any function that accepts any subclass of `xmap` should be named using the `xmap_` prefix convention -- e.g. `xmap_validate()`
- generics that will form part of a user workflow should follow the `xmap_` prefix convention (e.g. `xmap_validate()`). This makes reduces ambiguity when using these functions in a conformr workflow.
For functions return `xmap` subclasses as output:
- any function that returns a specific subclass of `xmap` should end with the suffice `_<subclass>`. For example `as_xmap_df()` and `new_xmap_df()`
### Reference Index
Draft [pkgdown function reference](https://pkgdown.r-lib.org/articles/pkgdown.html#reference) to be placed in `_pkgdown.yml`
``` yml
reference:
- title: "Overview"
- "xmap-package"
- "xmap_df-class"
- title: "Creation and Coercion"
desc: >
Functions for constructing a `xmap_df`.
- xmap
- as_xmap_df
- title: "Helpers and Validation"
- new_xmap
- validate_xmap
- starts_with("has", internal = TRUE)
```
### Graph & Matrix concepts
- graph notation reference: <http://www-student.cse.buffalo.edu/~atri/cse331/support/notation/graphs.html>; <https://www3.nd.edu/~dgalvin1/60610/60610_S09/60610graphnotation.pdf>
### Toy Examples
```{r ideal-xmap}
## define some test data here
input_df <- tibble::tribble(
~from, ~to, ~weights,
"A1", "B01", 1,
"A2", "B02", 1,
"A3", "B02", 1,
"A4", "B03", 0.25,
"A4", "B04", 0.75
)
int_dat <- list("input_df" = input_df)
usethis::use_data(int_dat, internal = TRUE, overwrite = TRUE)
```
```{r simple-xmap}
simple_xmap <- tibble::tribble(
~f, ~t, ~w,
"x1111", "A1", 1,
"x2222", "B2", 0.5,
"x2222", "B3", 0.5,
"x3333", "C5", 1,
"x4444", "C5", 1,
"x5555", "D6", 0.4,
"x5555", "D7", 0.6,
"x6666", "D6", 0.3,
"x6666", "D7", 0.7,
"x7777", "D6", 1
)
```
### API Design & Functionality
[Issue #67 Comment](https://github.com/cynthiahqy/conformr-project/issues/67#issuecomment-1436365643):
I'm not sure offering helpers for modifying crossmaps is necessary or even desirable.
- Lists of maps make more sense from a "using xmaps" perspective,
- Combining multiple crossmaps into a single table add a flexible quality to xmaps that goes against the purpose of the structure as a data-provenance object.
- Users can still manipulate and store multiple sets of weights or other xmap variants in a "parent table", from which they create multiple xmap.
- Manipulation of xmaps creates risk around invalidating the map -- i.e. modifying values in the weights column is technically possible for an xmap (since it is just a data.frame column), but not desirable since the map is not revalidated after the manipulation -- i.e. `xmap |> dplyr::mutate()` should probably return a tibble rather than an xmap.
[Issue #93: 14 Apr 2023](https://github.com/cynthiahqy/conformr-project/issues/93#issuecomment-1508073958)
- Rather than classes, I think it makes the most sense to have a single xmap class (i.e. xmap_df), and everything else be "candidate links" -- which can be input into the as_xmap() generic.
- Candidate links can also be validated as crossmaps, without coercion, allowing users to validate transformation objects in existing workflows. Coercion into xmap classes should be reserved for facilitating "advanced" or "extension" tasks --- i.e. visualisation, perturbation, multi-map transformations.
- Some xmap class variants could include:
- "long" or "short" formats for ggplot;
- recode/collapse variants which drop the weights columns (since it is implied);
- igraph objects for spatial aggregation/transformation -- noting the similarity between spatial weighting matrices and crossmaps (see this Vignette from [SpatialReg](https://r-spatial.github.io/spatialreg/articles/nb_igraph.html).
## Mock Objects
```{r}
usethis::use_data_raw("mock", open = FALSE)
```
```{r mock-objects, send_to="data-raw/mock.R"}
mock <- list()
mock$named_ctr_iso3c <- countrycode::codelist |>
dplyr::select(iso3c, iso.name.en) |>
tidyr::drop_na() |>
tibble::deframe()
# mock_named$collapse_list <- list(MAMM = c("elephant", "whale", "monkey"),
# REPT = c("lizard", "turtle"),
# CRUS = c("crab"))
mock$df_anzsco21 <- strayr::anzsco2021 |>
dplyr::select(tidyselect::starts_with(c("anzsco_major", "anzsco_submajor"))) |>
dplyr::distinct() |>
dplyr::select(tidyselect::ends_with("_code"), tidyselect::everything())
mock$xmap_abc <- tibble::tribble(
~lower, ~upper, ~share,
"a", "AA", 1, # one-to-one
"b", "BB", 1, # one-FROM-many
"c", "BB", 1,
"d", "CC", 0.3, # one-to-many
"d", "DD", 0.6,
"d", "EE", 0.1
) |>
xmap::as_xmap_df(from = lower, to = upper, weights = share)
mock$named_aus <- list(AUS = c("AU-NSW", "AU-QLD", "AU-SA", "AU-TAS", "AU-VIC", "AU-WA", "AU-ACT", "AU-NT"))
mock$df_aus_pop <- tibble::tribble(
~state_name, ~state, ~pop,
"New South Wales", "AU-NSW", 8153600,
"Victoria", "AU-VIC", 6613700,
"Queensland", "AU-QLD", 5322100,
"South Australia", "AU-SA", 1820500,
"Western Australia", "AU-WA", 2785300,
"Tasmania", "AU-TAS", 571500,
"Northern Territory", "AU-NT", 250600,
"Australian Capital Territory", "AU-ACT", 456700
) |>
dplyr::mutate(ctr = "AUS")
usethis::use_data(mock)
```
```{r document-mock-objects, send_to="R/data.R"}
#' Mock input objects for the `xmap` package
#'
#' A collection of mock inputs for experimenting with functions
#' in the `xmap` package.
#' `named_` objects are either named vectors or nested lists.
#' `df_` objects may contain source-target *pairs* (no weights),
#' or weighted source-target *links*.
#'
#' @format ## `mock`
#' A list with:
#' \describe{
#' \item{named_ctr_iso3c}{named vector with 249 elements. Names are ISO-3 country codes, values are ISO English country names. Retrieved from `countrycode` package:
#' \url{https://github.com/vincentarelbundock/countrycode}}
#' \item{df_anzsco21}{tibble with 51 rows and 4 columns. Contains major and submajor occupation codes and descriptions for ANZSCO21. Retrieved from `strayr` package:
#' \url{https://github.com/runapp-aus/strayr}}
#' \item{xmap_abc}{xmap_df: lower -> upper BY share. Mock crossmap with 6 links including one-to-one, one-to-many and many-to-one relations.}
#' \item{named_aus}{named list with 1 element named "AUS" containing codes for the Australian states}
#' \item{df_aus_pop}{tibble containing 2022 population figures for Australia by state. Retrieved from:
#' \url{https://www.abs.gov.au/statistics/people/population/national-state-and-territory-population/jun-2022}}
#' }
#' @examples
#' links_aus_agg <- mock$named_aus |>
#' as_pairs_from_named(names_to = "ctr", values_to = "state") |>
#' add_weights_unit() |>
#' dplyr::select(ctr, state, weights) |>
#' verify_links_as_xmap(from = state, to = ctr, weights)
#' links_aus_agg
#'
#' links_aus_split_equal <- links_aus_agg |>
#' add_weights_equal(from = ctr, to = state) |>
#' dplyr::select(ctr, state, weights) |>
#' verify_links_as_xmap(from = ctr, to = state, weights)
#' links_aus_split_equal
#'
#' links_aus_split_pop <- mock$df_aus_pop |>
#' add_weights_prop(from = ctr, to = state, prop = pop)
#' links_aus_split_pop
"mock"
```
## Candidate Links
### Convert: List to Links Data Frame
One-to-one and many-to-one mappings could easily be encoded as list objects, where each element of the list is a member of the target set, and contains a vector of all the source nodes that link to it. For instance:
```{r}
link_list <- list(
AA = c("x3", "x4", "x6"),
BB = c("x1", "x5"),
CC = c("x2")
)
```
Convert to tibble:
```{r}
col_from <- "source"
col_to <- "target"
col_weights <- "weights"
link_list |>
tibble::enframe(name = col_to, value = col_from) |>
tidyr::unnest_longer(col = c(col_from)) |>
dplyr::mutate("{col_weights}" := 1)
```
Convert to dataframe: -- how to unnest???
```{r}
# convert list to data.frame
links <- as.matrix(link_list) |>
as.data.frame()
# convert row names to column
from_name <- "source"
to_name <- "target"
links[[to_name]] <- row.names(links)
names(links)[1] <- from_name
```
``` r
xmap::pairs_from_named(list = link_list,
col_from = "source",
col_to = "target",
col_weights = "weights")
```
#### Helper: Node pairs from Named List or Vector
`tibble::enframe` is:
``` r
tibble(
name = names(islands),
size = islands
)
```
```{r fnc-pairs-from-named, send_to="R/pairs_named.R"}
#' Convert between column pairs and named vector or lists
#'
#' @description
#' Convert named vectors or nested lists into a two-column table of node pairs and vice versa.
#' `as_pairs_from_named` extracts the vector or list element names and the values, unnesting where necessary.
#' `pairs_to_named_vector` extracts name-value pairs from column pairs as is,
#' whilst `pairs_to_named_list()` nests the values first.
#'
#' @inheritParams verify_named
#' @inheritParams verify_pairs
#' @param names_to,values_to character vector specify the new columns to pass the information in `x` into.
#' @param names_from,values_from two columns in `x` to convert to names and values
#'
#' @return
#' * For `as_pairs_from_named()`: a two-column tibble
#' * For `pairs_to_named` fncs: named vector or list
#'
#' @name as_pairs
#' @examples
#' # Coerce named vectors and list to column pairs
#'
#' veg_vec <- c(eggplant = "aubergine", zucchini = "courgette")
#' as_pairs_from_named(veg_vec, "au_eng", "uk_eng")
#'
#' animal_list <- list(
#' MAMM = c("elephant", "whale", "monkey"),
#' REPT = c("lizard", "turtle"),
#' CRUS = c("crab")
#' )
#' as_pairs_from_named(animal_list, "class", "animal")
#'
#' # Convert pairs back to named vector and lists
#' veg_from_pairs <- as_pairs_from_named(veg_vec) |>
#' pairs_to_named_vector(names_from = name, values_from = value)
#' identical(veg_vec, veg_from_pairs)
#'
#' animal_from_pairs <- as_pairs_from_named(animal_list, "class", "animal") |>
#' pairs_to_named_list(names_from = class, values_from = animal)
#' identical(animal_list, animal_from_pairs)
NULL
#' @describeIn as_pairs Convert named vector or nested list into column pairs
#' @export
as_pairs_from_named <- function(x, names_to = "name", values_to = "value") {
stopifnot(is.vector(x))
node_pairs <- x |>
tibble::enframe(name = names_to, value = values_to) |>
tidyr::unnest_longer(col = tidyr::all_of(values_to))
return(node_pairs)
}
```
#### Helper: Named list from pairs `pairs_to_named()`
```{r send_to="R/pairs_named.R"}
#' @describeIn as_pairs Convert column pairs to named vector
#' @export
pairs_to_named_vector <- function(df, names_from = name, values_from = value) {
ordered_cols <- dplyr::select(df, {{ names_from }}, {{ values_from }})
tibble::deframe(ordered_cols)
}
#' @describeIn as_pairs Convert column pairs to nested named list
#' @export
pairs_to_named_list <- function(df, names_from = name, values_from = value) {
nested_cols <- dplyr::select(df, {{ names_from }}, {{ values_from }}) |>
tidyr::nest(values = {{ values_from }})
ordered_cols <- dplyr::select(nested_cols, {{ names_from }}, values)
tibble::deframe(ordered_cols) |>
sapply(as.matrix) |>
sapply(as.vector) |>
as.list()
}
```
#### Helper: Add weights to pairs
```{r fnc-add-weights-unit, send_to="R/add_weights.R"}
#' Add weights to unweighted links
#'
#' Attach column of weights to a table of unweighted source-target links.
#' If calculating equal fractional weights, uses distinct `from`-`to` pairs.
#' The resultant weighted links can be verified or coerced into `xmap`.
#'
#' @inheritParams verify_pairs
#' @param prop numeric column containing reference values to calculate fractional weights from.
#' Weights are calculated as `prop/sum(prop)` where the sum is calculated separately for each set of links coming out of a given `from` node.
#' @param weights_into character string naming new column to store link weights in
#'
#' @return `df` with additional column of weights
#' @name add_weights
NULL
#' @describeIn add_weights Attach column of unit weights (i.e. ones)
#' @export
#' @examples
#' # simple unit weights
#' AUS_pairs <- list(AUS = c("NSW", "QLD", "SA", "TAS", "VIC", "WA", "ACT", "NT")) |>
#' as_pairs_from_named(names_to = "ctr", values_to = "state")
#' AUS_pairs |>
#' add_weights_unit(weights_into = "weights")
#'
add_weights_unit <- function(df, weights_into = "weights") {
df[, weights_into] <- 1
return(df)
}
```
```{r}
testthat::test_that("add_weights_unit() works as expected", {
# unit
abc_pairs <- data.frame(lower = letters[1:5], upper = LETTERS[1:5])
abc_links <- data.frame(lower = letters[1:5], upper = LETTERS[1:5], weights = 1)
testthat::expect_equal(add_weights_unit(abc_pairs), abc_links)
})
```
### Link Properties: `vhas_*(x_)`
`vhas_*(v_)` functions take in vector arguments only, and are designed to be able to validate the graph features of non-data.frame xmaps (so long as the links can be decomposed into from,to,weight vectors).
```{r send_to="R/vhas.R"}
#' Boolean flags for properties of candidate and validated xmap links (internal)
#'
#' @description
#' `vhas_*()` functions check properties of xmap links and/or candidate links.
#' The functions only accepts equal length vector inputs to support multiple link formats,
#' but does not check if the inputs are from the same xmap.
#' @param v_from,v_to,v_weights equal length vectors containing the source-target node pairs
#'
#' @return TRUE or FALSE
#'
#' @name vhas
NULL
```
#### Crossmap Property Flags
A valid Crossmap satisfies the following conditions:
1. There is at most one link between each distinct source and target node (`has_dup_pairs()`)
2. For each source node, the sum of weights attached to all outgoing links sums to one. (`has_complete_weights()`)
```{r send_to="R/vhas.R"}
#' @describeIn vhas Returns TRUE if xmap does not have
#' duplicate pairs of source-target nodes (irrespective of weights)
#'
vhas_no_dup_pairs <- function(v_from, v_to) {
stopifnot(is.vector(v_from))
stopifnot(is.vector(v_to))
stopifnot(identical(length(v_from), length(v_to)))
links <- data.frame(v_from, v_to)
dup_idx <- anyDuplicated(links)
!as.logical(dup_idx)
}
```
```{r send_to="R/vhas.R"}
#' @describeIn vhas Returns TRUE if all weights for a given `from` label
#' sum to one (approximately)
#' @param tol numeric \eqn{\ge 0}. Ignore differences smaller than `tol`.
#' Passed through to the `tolerance` arg of `base::all.equal()`.
vhas_complete_weights <- function(v_from, v_weights, tol = .Machine$double.eps^0.5) {
stopifnot(is.vector(v_from))
stopifnot(is.vector(v_weights))
stopifnot(identical(length(v_from), length(v_weights)))
sum_w <- tapply(
X = v_weights,
INDEX = v_from,
FUN = sum,
simplify = TRUE
) |> as.vector()
names(sum_w) <- NULL
ones <- rep(1, length(sum_w))
all(isTRUE(all.equal(sum_w, ones, tolerance = tol)))
}
```
```{r send_to="R/vhas.R"}
.calc_vector_lens <- function(...) {
v_list <- list(...)
v_lens <- sapply(v_list, length)
return(v_lens)
}
```
```{r send_to="R/vhas.R"}
#' @describeIn vhas Returns TRUE if links have no duplicate pairs and complete weights
vhas_xmap_props <- function(v_from, v_to, v_weights) {
## check vectors are equal length
v_lengths <- .calc_vector_lens(v_from, v_to, v_weights)
stopifnot(length(unique(v_lengths)) == 1)
## check properties
v_props <- c(
pairs = vhas_no_dup_pairs(v_from, v_to),
weights = vhas_complete_weights(v_from, v_weights)
)
all(v_props)
}
```
```{r test-has-flags}
testthat::test_that(
"vhas_* xmap validation helpers work as expected on valid df",
{
df <- tibble::tribble(
~from, ~to, ~weights,
"A1", "B01", 1,
"A2", "B02", 1,
"A3", "B02", 1,
"A4", "B03", 0.67,
"A4", "B04", 0.33
)
testthat::expect_true(vhas_no_dup_pairs(df$from, df$to))
testthat::expect_true(vhas_complete_weights(df$from, df$weights))
testthat::expect_true(vhas_xmap_props(df$from, df$to, df$weights))
}
)
testthat::test_that(
"vhas_* xmap validation helpers catch invalid df",
{
df <- tibble::tribble(
~from, ~to, ~weights,
"A1", "B01", 1,
"A2", "B02", 0.3,
"A2", "B02", 0.5
)
testthat::expect_false(vhas_complete_weights(df$from, df$weights))
testthat::expect_false(vhas_no_dup_pairs(df$from, df$to))
}
)
testthat::test_that(
"vhas_complete_weights() works on recurring fractional weights",
{
df <- data.frame(
key1 = rep("A1", 3),
key2 = c("B01", "B02", "B03"),
share = rep(1 / 3, 3)
)
testthat::expect_true(vhas_complete_weights(df$key1, df$share))
}
)
```
#### Relation Type Flags
- used for print methods, reverse
```{r print-helpers, send_to="R/vhas.R"}
#' @describeIn vhas Return TRUE if xmap recodes labels between `from` and `to`
vhas_1to1 <- function(v_weights) {
stopifnot(is.vector(v_weights))
any(v_weights == 1)
}
#'
vhas_recode <- vhas_1to1
#' @describeIn vhas Return TRUE if xmap has splitting links between `from` and `to`
vhas_1toM <- function(v_weights) {
stopifnot(is.vector(v_weights))
any(v_weights < 1)
}
#'
vhas_split <- vhas_1toM
#' @describeIn vhas Return TRUE if xmap has collapsing links between `from` and `to`
vhas_1fromM <- function(v_to) {
stopifnot(is.vector(v_to))
as.logical(anyDuplicated(v_to))
}
#'
vhas_collapse <- vhas_1fromM
```
```{r}
testthat::test_that(
"vhas_* relation type flag functions work as expected",
{
w_1to1 <- rep(1, 10)
w_1toM <- rep(1 / 6, 6)
to_1fromM <- rep("country", 4)
testthat::expect_true(vhas_recode(w_1to1))
testthat::expect_false(vhas_recode(w_1toM))
testthat::expect_true(vhas_split(w_1toM))
testthat::expect_false(vhas_split(w_1to1))
testthat::expect_true(vhas_collapse(to_1fromM))
}
)
```
### Helper: df property checks
#### Abort Missing Columns
```{r send_to="R/abort.R"}
#' @describeIn abort Abort if named columns can't be found in df
#'
abort_missing_cols <- function(df, cols) {
missing_cols <- setdiff(cols, names(df))
if (length(missing_cols) != 0) {
cli::cli_abort(
message = "The column{?s} {.var {missing_cols}} {?was/were} not found.",
class = "abort_missing_cols"
)
}
invisible(df)
}
```
#### Abort Missing Values
```{r send_to="R/abort.R"}
#' @describeIn abort Abort if xmap_df has missing values
#'
abort_any_na <- function(df) {
if (base::anyNA(df)) {
cli::cli_abort(
message = "NA values found. Please enter missing `from` or `to` node labels and/or convert NA weights",
class = "abort_na"
)
}
invisible(df)
}
```
### Verify: Named
- note that `list(fruit = c("apple", "banana"))` and `c(fruit = c("apple", "banana"))` return different `names()`. `c()` generates unique names: `fruit1` and `fruit2`:
``` r
# > c(fruit = c("apple", "banana"))
# fruit1 fruit2
# "apple" "banana"
```
```{r send_to="R/verify_named.R"}
#' Verify crossmap properties of named vectors or lists
#'
#' @param x a Named vector or list. Lists values are flattened via `unlist()`.
#'
#' @return `x` or throws an error
#' @name verify_named
#' @examples
#' ## check each fruit has a unique color
#' fruit_color <- c(apple = "green", strawberry = "red", banana = "yellow")
#' verify_named_all_1to1(fruit_color)
#'
#' ## check no student is assigned to multiple groups
#' student_groups <- list(
#' GRP1 = c("kate", "jane", "peter"),
#' GRP2 = c("terry", "ben", "grace"),
#' GRP3 = c("cindy", "lucy", "alex")
#' )
#' verify_named_no_dup_names(student_groups)
#'
#' ## check
NULL
```
Verify pairwise properties:
```{r send_to="R/verify_named.R"}
#' @describeIn verify_named Verify named vector or list has only one-to-one relations
#' @export
#'
verify_named_all_1to1 <- function(x) {
stopifnot(is.vector(x))
unique_names <- unique(names(x))
unique_values <- unique(unlist(unname(x)))
stop <- !(length(unique_names) == length(unique_values))
if (stop) {
cli::cli_abort("Not all relations in `x` are 1-to-1.",
class = "abort_not_1to1"
)
}
invisible(x)
}
#' @describeIn verify_named Verify name-value pairs of named vector or list are not duplicated
#' @export
verify_named_all_unique <- function(x) {
stopifnot(is.vector(x))
pairs <- as_pairs_from_named(x)
dup_idx <- anyDuplicated(pairs)
stop <- as.logical(dup_idx)
if (stop) {
cli::cli_abort(
c(
"Duplicated pairs found in `x`.",
"i" = "Use `as_pairs_from_named(x) |> base::duplicated()` to identify duplicates."
),
class = "abort_not_unique"
)
}
invisible(x)
}
#' @describeIn verify_named Verify names of named vector or list are not duplicated
#' @export
verify_named_all_names_unique <- function(x) {
stopifnot(is.vector(x))
dup_idx <- anyDuplicated(names(x))
stop <- as.logical(dup_idx)
if (stop) {
cli::cli_abort(
c(
"Duplicated names found in `x`.",
"i" = "Use `base::duplicated(names(x))` to identify duplicates."
),
class = "abort_not_unique"
)
}
invisible(x)
}
#' @describeIn verify_named Verify values in named vector or list are not duplicated (after unnesting)
#' @export
verify_named_all_values_unique <- function(x) {
stopifnot(is.vector(x))
dup_idx <- anyDuplicated(unlist(unname(x)))
stop <- as.logical(dup_idx)
if (stop) {
cli::cli_abort(
c(
"Duplicated values found in `x`.",
"i" = "Use `base::duplicated(unlist(unname(x)))` to identify duplicates."
),
class = "abort_not_unique"
)
}
# stopifnot(unlist(unname(x)) == unique(unlist(unname(student_groups))))
invisible(x)
}
```
```{r}
testthat::test_that("verify_named_all_1to1() works as expected", {
v1toM <- c(fruit = "apple", fruit = "banana")
v1to1 <- c(A = 1, B = 2, C = 3)
l1toM <- list(fruit = c("apple", "banana"))
testthat::expect_error(verify_named_all_1to1(v1toM), class = "abort_not_1to1")
testthat::expect_error(verify_named_all_1to1(l1toM), class = "abort_not_1to1")
testthat::expect_equal(verify_named_all_1to1(v1to1), v1to1)
})
testthat::test_that("verify_named_*_unique() work as expected", {
vdup_pairs <- c(fruit = "apple", fruit = "apple")
ldup_pairs <- list(fruit = c("apple", "apple"))
testthat::expect_error(verify_named_all_unique(vdup_pairs), class = "abort_not_unique")
testthat::expect_error(verify_named_all_unique(ldup_pairs), class = "abort_not_unique")
vdup_names <- c(fruit = "apple", fruit = "banana")
ldup_names <- list(fruit = c("apple", "banana"), fruit = "pear")
testthat::expect_error(verify_named_all_names_unique(vdup_names), class = "abort_not_unique")
testthat::expect_error(verify_named_all_names_unique(ldup_names), class = "abort_not_unique")
vdup_values <- c(fruit = "apple", veg = "apple")
ldup_values <- list(fruit = c("apple", "banana"), veg = "apple")
testthat::expect_error(verify_named_all_values_unique(vdup_values), class = "abort_not_unique")
testthat::expect_error(verify_named_all_values_unique(ldup_values), class = "abort_not_unique")
})
```
```{r send_to="R/verify_named.R"}
#' @describeIn abort Abort message for verify_named_matchset_* functions
#' @export
msg_abort_named_matchset <- function(set_type = c("names", "values"),
match_type = c("exact", "within", "contain")) {
match_text <- switch(match_type,
exact = "do not exactly match",
within = "are not all within",
contain = "do not contain all elements of"
)
cli::format_error("The {set_type} of {.var x} {match_text} {.var ref_set}")
}
#' Verify unique names or values of named vector or list match expected set
#'
#' @name verify_named_matchset
#' @inheritParams verify_named
#' @param ref_set a vector of character strings
#'
#' @return `x` or throw an error
#' @examples
#' fruit_color <- c(apple = "green", strawberry = "red", banana = "yellow")
#' fruit_set <- c("apple", "strawberry", "banana", "pear")
#' fruit_color |>
#' verify_named_matchset_names_within(ref_set = fruit_set)
NULL
#' @describeIn verify_named_matchset Names of `x` **exactly** match `ref_set`
#' @export
verify_named_matchset_names_exact <- function(x, ref_set) {
stopifnot(is.vector(x))
unique_names <- unique(names(x))
stop <- !setequal(ref_set, unique_names)
if (stop) {
cli::cli_abort(msg_abort_named_matchset("names", "exact"),
class = "abort_matchset"
)
}
invisible(x)
}
#' @describeIn verify_named_matchset Values of `x` **exactly** match `ref_set`
#' @export
verify_named_matchset_values_exact <- function(x, ref_set) {
stopifnot(is.vector(x))
unique_values <- unique(unlist(unname(x)))
stop <- !setequal(ref_set, unique_values)
if (stop) {
cli::cli_abort(msg_abort_named_matchset("values", "exact"),
class = "abort_matchset"
)
}
invisible(x)
}
#' @describeIn verify_named_matchset Names of `x` **contain** all of `ref_set`
#' @export
verify_named_matchset_names_contain <- function(x, ref_set) {
stopifnot(is.vector(x))
unique_names <- unique(names(x))
stop <- !all(ref_set %in% unique_names)
if (stop) {
cli::cli_abort(msg_abort_named_matchset("names", "contain"),
class = "abort_matchset"
)
}
invisible(x)
}
#' @describeIn verify_named_matchset Values of `x` **contain** all of `ref_set`
#' @export
verify_named_matchset_values_contain <- function(x, ref_set) {
stopifnot(is.vector(x))
unique_values <- unique(unlist(unname(x)))
stop <- !all(ref_set %in% unique_values)
if (stop) {
cli::cli_abort(msg_abort_named_matchset("values", "contain"),
class = "abort_matchset"
)
}
invisible(x)
}
#' @describeIn verify_named_matchset Names of `x` are all **within** `ref_set`
#' @export
verify_named_matchset_names_within <- function(x, ref_set) {
stopifnot(is.vector(x))
unique_x <- unique(names(x))
stop <- !all(unique_x %in% ref_set)
if (stop) {
cli::cli_abort(msg_abort_named_matchset("names", "within"),
class = "abort_matchset"
)
}
invisible(x)
}
#' @describeIn verify_named_matchset Values of `x` are all **within** `ref_set`