Last updated: 2023-01-18

Checks: 7 0

Knit directory: viz-panel-maps/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20221110) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version e2d4fc1. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    README_files/
    Ignored:    renv/library/
    Ignored:    renv/staging/

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/factor-xmaps.Rmd) and HTML (docs/factor-xmaps.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd e2d4fc1 cynthiahqy 2023-01-18 workflowr::wflow_publish(files = "analysis/factor-xmaps.Rmd")

Background

  • Factors are the base R S3 class for categorical variables
  • Factors are integer vectors with a levels attribute.
  • forcats provides convenience and safe-guarded functions for working with factors

Visualisation Idea

  • Take levels before and after transformation, generate and visualise the implicit xmap.
fct <- factor(c("a", "b", "b", "c", "d"))

after_other <- fct |>
  forcats::fct_other(keep = c("a", "b"), other_level = "other")
stopifnot(identical(after_other, factor(c("a", "b", "b", "other", "other"))))

For reference this is the mapping:

xmap_ref <-
  tibble::tribble(~key1, ~key2, ~weight,
                  "a", "a", 1,
                  "b", "b", 1,
                  "c", "other", 1,
                  "d", "other", 1)

We can probably only extract the mapping if there is at most one target node involved in a many-to-one mapping.

collapse_xmap <- tibble::tibble(
  key1 = setdiff(fct, after_other),
  key2= setdiff(after_other, fct)
  )

preserve_xmap <- tibble::tibble(
  key1 = intersect(fct, after_other),
  key2 = key1
)

xmap_set <- dplyr::bind_rows(preserve_xmap, collapse_xmap) |>
  dplyr::mutate(weight = 1)

identical(xmap_set, xmap_ref)
[1] TRUE

Visualising it

require(dplyr)
Loading required package: dplyr

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
require(ggplot2)
Loading required package: ggplot2
require(ggbump)
Loading required package: ggbump
plt_pm_df <- function(pm, from, to, weights){

  edges <- pm |>
    transmute(from = {{from}}, to = {{to}}, weighted = {{weights}})

  ## calculate positions for nodes
  from_nodes <- distinct(edges, from) |> mutate(from_y = row_number())
  to_nodes <- distinct(edges, to) |> mutate(to_y = row_number() - 1 + 0.5)

  ## generate df for ggplot
  df <- edges |>
    ## generate mapping type/case variables
    group_by(from) |>
    mutate(n_dest = n()) |>
    ungroup() |>
    group_by(to) |>
    mutate(n_origin = n(),
           min_weight = min(weighted)) |>
    ungroup() |>
    mutate(value_case = case_when(n_dest == 1 ~ "one-to-one",
                                  n_dest > 1 ~ "one-to-many")) |>
    left_join(tribble(~value_case, ~line_type, ~font_type,
                      "one-to-one", "solid", "bold",
                      "one-to-many", "dashed", "italic"),
              by = "value_case") |>
    mutate(map_case = case_when(n_origin > 1 & n_dest > 1 ~ "many-from-many",
                                n_origin == 1 & n_dest > 1 ~ "many-from-one",
                                n_origin > 1 & n_dest == 1 ~ "one-from-many",
                                n_origin == 1 & n_dest == 1 ~ "one-from-one")) |>
    mutate(from_case = case_when(n_origin == 1 ~ "one-from-one",
                                 n_origin > 1 ~ "one-from-many",
                                 n_origin < 1 ~ "ERROR! origin codes < 1"),
           dest_case = case_when(min_weight < 1 ~ "contains split",
                                 min_weight == 1 ~ "aggregation only",
                                 min_weight > 1 ~ "ERROR! weight > 1")
    ) |>
    ## add y-coordinates
    left_join(from_nodes, by = "from") |>
    left_join(to_nodes, by = "to") |>
    ## add x-coordinates
    mutate(from_x = 0,
           to_x = 5) |>
    ## give each from-out instruction a unique id
    mutate(idx = row_number())

  plt <- df |>
    ggplot(aes(x = from_x, xend = to_x, y = from_y, yend = to_y, group = idx)) +
    ## edges as sigmoid curves with line type
    geom_sigmoid(aes(linetype = I(line_type))) +
    # to/from nodes
    scale_y_reverse() +
    geom_text(aes(x = from_x - 0.5, label=from, fontface=I(font_type) )) +
    geom_label(aes(x = to_x + 0.5, y = to_y, label=to, fill = dest_case)) +
    # edge labels
    geom_label(data = filter(df, value_case == "one-to-many"),
               aes(x = (((from_x + to_x) / 2) + to_x) / 2,
                   y = to_y,
                   label = scales::percent(weighted,5),
                   alpha = weighted),
               fill = "gray") +
    geom_label(data = filter(df, value_case == "one-to-one"),
               aes(x = (from_x + to_x) / 4,
                   y = from_y,
                   label = weighted)) +
    # theme
    scale_fill_manual(values = wesanderson::wes_palette(n = 4, name = "GrandBudapest2")) +
    scale_color_manual(values = wesanderson::wes_palette(n = 4, name = "GrandBudapest2")) +
    cowplot::theme_minimal_grid(font_size = 14, line_size = 0) +
    theme(legend.position = "bottom",
          panel.grid.major = element_blank(),
          axis.text.y = element_blank(),
          axis.text.x = element_blank(),
          plot.background = element_rect(fill = "white")) +
    labs(x = NULL, y = NULL, fill = "Target", fontface="Source")

  return(plt)
}
plt_pm_df(xmap_set, from = key1, to = key2, weights = weight)


sessionInfo()
R version 4.2.1 (2022-06-23)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur ... 10.16

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

other attached packages:
[1] ggbump_0.1.0    ggplot2_3.3.6   dplyr_1.0.10    workflowr_1.7.0

loaded via a namespace (and not attached):
 [1] tidyselect_1.2.0  xfun_0.31         bslib_0.3.1       colorspace_2.0-3 
 [5] vctrs_0.4.2       generics_0.1.3    htmltools_0.5.2   yaml_2.3.5       
 [9] utf8_1.2.2        rlang_1.0.6       jquerylib_0.1.4   later_1.3.0      
[13] pillar_1.8.1      glue_1.6.2        withr_2.5.0       DBI_1.1.3        
[17] lifecycle_1.0.3   stringr_1.4.1     munsell_0.5.0     gtable_0.3.1     
[21] evaluate_0.16     labeling_0.4.2    knitr_1.39        forcats_0.5.1    
[25] callr_3.7.0       fastmap_1.1.0     httpuv_1.6.5      ps_1.7.1         
[29] fansi_1.0.3       highr_0.9         Rcpp_1.0.9        renv_0.15.5      
[33] promises_1.2.0.1  scales_1.2.1      jsonlite_1.8.2    farver_2.1.1     
[37] fs_1.5.2          digest_0.6.30     stringi_1.7.8     processx_3.6.1   
[41] getPass_0.2-2     cowplot_1.1.1     rprojroot_2.0.3   grid_4.2.1       
[45] cli_3.4.1         tools_4.2.1       magrittr_2.0.3    sass_0.4.2.9000  
[49] tibble_3.1.8      wesanderson_0.3.6 whisker_0.4       pkgconfig_2.0.3  
[53] assertthat_0.2.1  rmarkdown_2.14    httr_1.4.3        rstudioapi_0.13  
[57] R6_2.5.1          git2r_0.30.1      compiler_4.2.1