|
a |
|
b/R/GatherGraphEdge.R |
|
|
1 |
#' Gather graph edge from data frame |
|
|
2 |
#' Please note that this function is from the 'ggraph' package and has not been altered in functionality, |
|
|
3 |
#' but it has been optimized and iterated. |
|
|
4 |
#' It is not original content of 'TransProR'. |
|
|
5 |
#' However, since 'ggraph' caused frequent GitHub Action errors during the creation of 'TransProR', |
|
|
6 |
#' the author directly referenced the involved functions in 'TransProR'. |
|
|
7 |
#' This is not the author's original creation. All users please be aware! |
|
|
8 |
#' @param df A data frame |
|
|
9 |
#' @param index A vector of column names to group by |
|
|
10 |
#' @param root Root name for the root node connections, optional |
|
|
11 |
#' @return A tibble of graph edges |
|
|
12 |
#' @export |
|
|
13 |
#' @importFrom dplyr mutate select group_by summarise bind_rows all_of across |
|
|
14 |
#' @importFrom tidyr unite |
|
|
15 |
#' @importFrom tibble as_tibble |
|
|
16 |
#' @name gather_graph_edge |
|
|
17 |
gather_graph_edge <- function(df, index = NULL, root = NULL) { |
|
|
18 |
if (length(index) < 2) { |
|
|
19 |
stop("Please specify at least two index columns.") |
|
|
20 |
} |
|
|
21 |
|
|
|
22 |
prepare_edge <- function(data, from, to, sep = "/") { |
|
|
23 |
data %>% |
|
|
24 |
tidyr::unite("from", dplyr::all_of(from), sep = sep, remove = FALSE) %>% |
|
|
25 |
tidyr::unite("to", dplyr::all_of(to), sep = sep) %>% |
|
|
26 |
dplyr::select(.data$from, .data$to) %>% |
|
|
27 |
dplyr::mutate(dplyr::across(c("from", "to"), as.character)) |
|
|
28 |
} |
|
|
29 |
|
|
|
30 |
edges <- lapply(seq_along(index)[-1], function(i) { |
|
|
31 |
prepare_edge(df, index[1:(i - 1)], index[1:i]) |
|
|
32 |
}) |
|
|
33 |
|
|
|
34 |
edges <- dplyr::bind_rows(edges) |
|
|
35 |
edges <- tibble::as_tibble(edges) |
|
|
36 |
|
|
|
37 |
if (!is.null(root)) { |
|
|
38 |
root_edges <- df %>% |
|
|
39 |
dplyr::group_by(.data[[index[1]]]) %>% |
|
|
40 |
dplyr::summarise(count = dplyr::n(), .groups = 'drop') %>% |
|
|
41 |
dplyr::mutate(from = root, to = as.character(.data[[index[1]]])) %>% |
|
|
42 |
dplyr::select(.data$from, .data$to) |
|
|
43 |
|
|
|
44 |
edges <- dplyr::bind_rows(root_edges, edges) |
|
|
45 |
} |
|
|
46 |
|
|
|
47 |
return(edges) |
|
|
48 |
} |