File: graph_manipulate.R

package info (click to toggle)
r-cran-graphlayouts 1.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,660 kB
  • sloc: cpp: 696; sh: 13; makefile: 2
file content (43 lines) | stat: -rw-r--r-- 1,262 bytes parent folder | download
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
#' @title Manipulate graph
#' @description functions to manipulate a graph
#'
#' @param g igraph object
#' @param attr edge attribute name used to sort edges
#' @param desc logical. sort in descending (default) or ascending order
#' @details `reorder_edges()` allows to reorder edges according to an attribute so that edges are
#' drawn in the given order.
#' @name graph_manipulate
#' @return manipulated graph
#' @examples
#' library(igraph)
#'
#' g <- sample_gnp(10, 0.5)
#' E(g)$attr <- 1:ecount(g)

#' gn <- reorder_edges(g,"attr")
#'
#' @author David Schoch
NULL

#' @rdname graph_manipulate
#' @export

reorder_edges <- function(g, attr, desc = TRUE) {
    if (!"name" %in% igraph::vertex_attr_names(g)) {
        igraph::V(g)$name <- 1:igraph::vcount(g)
    }
    edges_df <- igraph::as_data_frame(g, what = "edges")
    edges_df <- edges_df[order(edges_df[[attr]], decreasing = desc), ]

    vertices <- igraph::as_data_frame(g, what = "vertices")
    vattrs <- igraph::vertex_attr_names(g)
    idname <- which(vattrs == "name")
    vertices <- vertices[, c(idname, setdiff(seq_along(vattrs), idname))]

    gn <- igraph::graph_from_data_frame(
        d = edges_df,
        directed = igraph::is_directed(g),
        vertices = vertices
    )
    gn
}