-
Notifications
You must be signed in to change notification settings - Fork 10
/
convert_edges.R
59 lines (54 loc) · 2.07 KB
/
convert_edges.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
#' @title Convert edges
#' @description converts edges of an igraph/network/tidygraph object into format useable for edge bundling
#' @param object graph object
#' @param coords coordinates of vertices
#' @return data frame of edges with coordinates
#' @author David Schoch
#' @export
#'
convert_edges <- function(object, coords) UseMethod("convert_edges")
#' @rdname convert_edges
#' @method convert_edges default
#' @export
convert_edges.default <- function(object, coords) {
stop("don't know how to handle class ", dQuote(data.class(object)))
}
#' @rdname convert_edges
#' @method convert_edges igraph
#' @export
convert_edges.igraph <- function(object, coords) {
if (!requireNamespace("igraph", quietly = TRUE)) {
stop("The `igraph` package is required for this functionality")
}
el <- igraph::as_edgelist(object, names = FALSE)
if (igraph::vcount(object) != nrow(coords)) {
stop("number of rows in `coords` does not match number of vertices")
}
edges_xy <- cbind(coords[el[, 1], 1], coords[el[, 1], 2], coords[el[, 2], 1], coords[el[, 2], 2])
edges_xy
}
#' @rdname convert_edges
#' @method convert_edges network
#' @export
convert_edges.network <- function(object, coords) {
if (!requireNamespace("network", quietly = TRUE)) {
stop("The `network` package is required for this functionality")
}
el <- network::as.edgelist(object)
if (network::get.network.attribute(object, "n") != nrow(coords)) {
stop("number of rows in `coords` does not match number of vertices")
}
edges_xy <- cbind(coords[el[, 1], 1], coords[el[, 1], 2], coords[el[, 2], 1], coords[el[, 2], 2])
edges_xy
}
#' @rdname convert_edges
#' @method convert_edges tbl_graph
#' @export
convert_edges.tbl_graph <- function(object, coords) {
if (!requireNamespace("tidygraph", quietly = TRUE)) {
stop("The `tidygraph` package is required for this functionality")
}
el <- as.matrix(tidygraph::as_tibble(object, "edges"))
edges_xy <- cbind(coords[el[, 1], 1], coords[el[, 1], 2], coords[el[, 2], 1], coords[el[, 2], 2])
edges_xy
}