Short intergraph tutorial
Author: Michał Bojanowski

# Short `intergraph` tutorial

#### Michał Bojanowski

“Intergraph” is an R package with coercion routines for netowrk data objects. For more information, see

- Homepage on https://mbojan.github.io/intergraph/.
- Package development pages on https://github.com/mbojan/intergraph.

This is a short tutorial showing how to use functions in package “intergraph” using some example network data contained in the package.

# 1 Loading example data

To show the data, first load the packages.

    library(intergraph)
    library(network)

    ##
    ## 'network' 1.18.2 (2023-12-04), part of the Statnet Project
    ## * 'news(package="network")' for changes since last version
    ## * 'citation("network")' for citation information
    ## * 'https://statnet.org' for help, support, and other information

    library(igraph)

    ##
    ## Attaching package: 'igraph'

    ## The following objects are masked from 'package:network':
    ##
    ##     %c%, %s%, add.edges, add.vertices, delete.edges, delete.vertices,
    ##     get.edge.attribute, get.edges, get.vertex.attribute, is.bipartite,
    ##     is.directed, list.edge.attributes, list.vertex.attributes,
    ##     set.edge.attribute, set.vertex.attribute

    ## The following objects are masked from 'package:stats':
    ##
    ##     decompose, spectrum

    ## The following object is masked from 'package:base':
    ##
    ##     union

Now, these are the summaries of the “igraph” objects:

    summary(exIgraph)

    ## IGRAPH 258c8b4 D--- 15 11 --
    ## + attr: label (v/c), label (e/c)

    summary(exIgraph2)

    ## IGRAPH 66a1bae U--- 15 11 --
    ## + attr: label (v/c), label (e/c)

These are the summaries of the “network” objects:

    exNetwork

    ##  Network attributes:
    ##   vertices = 15
    ##   directed = TRUE
    ##   hyper = FALSE
    ##   loops = FALSE
    ##   multiple = FALSE
    ##   bipartite = FALSE
    ##   total edges= 11
    ##     missing edges= 0
    ##     non-missing edges= 11
    ##
    ##  Vertex attribute names:
    ##     label vertex.names
    ##
    ##  Edge attribute names:
    ##     label

    exNetwork2

    ##  Network attributes:
    ##   vertices = 15
    ##   directed = FALSE
    ##   hyper = FALSE
    ##   loops = FALSE
    ##   multiple = FALSE
    ##   bipartite = FALSE
    ##   total edges= 11
    ##     missing edges= 0
    ##     non-missing edges= 11
    ##
    ##  Vertex attribute names:
    ##     label vertex.names
    ##
    ##  Edge attribute names:
    ##     label

More information is available in the Appendix.

# 2 Functions `asNetwork` and `asIgraph`

Conversion of network objects between classes “network” and “igraph” can be performed using functions `asNetwork` and `asIgraph`.

## 2.1 network => igraph

Converting “network” objects to “igraph” is done by calling function `asIgraph` on a “network” object:

    # check class of 'exNetwork'
    class(exNetwork)

    ## [1] "network"

    # convert to 'igraph'
    g <- asIgraph(exNetwork)
    # check class of the result
    class(g)

    ## [1] "igraph"

Check if edgelists of the objects are identical

    el.g <- get.edgelist(g)

    ## Warning: `get.edgelist()` was deprecated in igraph 2.0.0.
    ## ℹ Please use `as_edgelist()` instead.
    ## This warning is displayed once every 8 hours.
    ## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    ## generated.

    el.n <- as.matrix(exNetwork, "edgelist")
    identical( as.numeric(el.g), as.numeric(el.n))

    ## [1] TRUE

## 2.2 igraph => network

Converting “igraph” objects to “network” is done by calling function `asNetwork` on an “igraph” object:

    net <- asNetwork(exIgraph)

Note the warning because of a “non-standard” network attribute `layout`, which is a function. Printing “network” objects does not handle non-standard attributes very well. However, all the data and attributes are copied correctly.

Check if edgelists of the objects are identical

    el.g2 <- get.edgelist(exIgraph)
    el.n2 <- as.matrix(net, "edgelist")
    identical( as.numeric(el.g2), as.numeric(el.n2))

    ## [1] TRUE

## 2.3 Handling attributes

Objects of class “igraph” and “network”, apart from storing actual network data (vertexes and edges), allow for adding attributes of vertexes, edges, and attributes of the network as a whole (called “network attributes” or “graph attributes” in the nomenclatures of packages “network” and “igraph” respectively).

Vertex and edge attributes are used by “igraph” and “network” in a largely similar fashion. However, network-level attributes are used differently. Objects of class “network” use network-level attributes to store various metadata, e.g., network size, whether the network is directed, is bipartite, etc. In “igraph” this information is stored separately.

The above difference affects the way the attributes are copied when we convert “network” and “igraph” objects into one another.

Both functions `asNetwork` and `asIgraph` have an additional argument `attrmap` that is used to specify how vertex, edge, and network attributes are copied. The `attrmap` argument requires a data frame. Rows of that data frame specify rules of copying/renaming different attributes. The data frame should have the following columns (all of class “character”):

- `type`: one of “network”, “vertex” or “edge”, whether the rule applies to network, vertex or edge attribute.
- `fromslc`: name of the which we are converting from
- `fromattr`: name of the attribute in the object we are converting from
- `tocls`: name of the class of the object we are converting to
- `toattr`: name of the attribute in the object we are converting to

The default rules are returned by a function `attrmap()`, these are:

    attrmap()

    ##      type fromcls  fromattr   tocls       toattr
    ## 1 network network  directed  igraph         <NA>
    ## 2 network network bipartite  igraph         <NA>
    ## 3 network network     loops  igraph         <NA>
    ## 4 network network     mnext  igraph         <NA>
    ## 5 network network  multiple  igraph         <NA>
    ## 6 network network         n  igraph         <NA>
    ## 7 network network     hyper  igraph         <NA>
    ## 8  vertex  igraph      name network vertex.names

For example, the last row specifies a rule that when an object of class “igraph” is converted to class “network”, then a vertex attribute `name` in the “igraph” object will be copied to a vertex attribute called `vertex.names` in the resulting object of class “network.

If the column `toattr` contains an `NA`, that means that the corresponding attribute is not copied. For example, the first row specifies a rule that when an object of class “network” is converted to class “igraph”, then a network attribute `directed` in the “network” object is not copied to the resulting object of class “igraph”.

Users can customize the rules, or add new ones, by constructing similar data frames and supplying them through argument `attrmap` to functions `asIgraph` and `asNetwork`.

As an example let us set the option to always drop the `na` vertex attribute. First, we need to setup the rule by adding an extra row to the data frame returned by `attrmap`:

    new_rule <- data.frame(type="vertex", fromcls="network", fromattr="na",
                           tocls="igraph", toattr=NA,
                           stringsAsFactors=FALSE)
    # combine with the default rules
    rules <- rbind( attrmap(), new_rule )
    rules

    ##      type fromcls  fromattr   tocls       toattr
    ## 1 network network  directed  igraph         <NA>
    ## 2 network network bipartite  igraph         <NA>
    ## 3 network network     loops  igraph         <NA>
    ## 4 network network     mnext  igraph         <NA>
    ## 5 network network  multiple  igraph         <NA>
    ## 6 network network         n  igraph         <NA>
    ## 7 network network     hyper  igraph         <NA>
    ## 8  vertex  igraph      name network vertex.names
    ## 9  vertex network        na  igraph         <NA>

Now we can use it with `asIgraph`:

    (ig1 <- asIgraph(exNetwork))

    ## IGRAPH 8fa0936 D--- 15 11 --
    ## + attr: label (v/c), na (v/l), vertex.names (v/c), label (e/c), na
    ## | (e/l)
    ## + edges from 8fa0936:
    ##  [1]  2-> 1  3-> 1  4-> 1  5-> 1  6-> 7  8-> 9 10->11 11->12 14->12 12->13
    ## [11] 13->14

    (ig2 <- asIgraph(exNetwork, amap=rules))

    ## IGRAPH d22eb45 D--- 15 11 --
    ## + attr: label (v/c), vertex.names (v/c), label (e/c), na (e/l)
    ## + edges from d22eb45:
    ##  [1]  2-> 1  3-> 1  4-> 1  5-> 1  6-> 7  8-> 9 10->11 11->12 14->12 12->13
    ## [11] 13->14

    # check if "na" was dropped
    "na" %in% igraph::vertex_attr_names(ig1)

    ## [1] TRUE

    "na" %in% igraph::vertex_attr_names(ig2)

    ## [1] FALSE

# 3 Network objects to/from data frames

Function `asDF` can be used to convert network object (of class “igraph” or “network”) to a list of two data frames:

    l <- asDF(exIgraph)
    str(l)

    ## List of 2
    ##  $ edges   :'data.frame':    11 obs. of  3 variables:
    ##   ..$ V1   : num [1:11] 2 3 4 5 6 8 10 11 12 13 ...
    ##   ..$ V2   : num [1:11] 1 1 1 1 7 9 11 12 13 14 ...
    ##   ..$ label: chr [1:11] "ba" "ca" "da" "ea" ...
    ##  $ vertexes:'data.frame':    15 obs. of  2 variables:
    ##   ..$ intergraph_id: int [1:15] 1 2 3 4 5 6 7 8 9 10 ...
    ##   ..$ label        : chr [1:15] "a" "b" "c" "d" ...

The resulting list has two components `edges` and `vertexes`. The `edges` component is essentially an edge list containing ego and alter ids in the first two columns. The remaining columns store edge attributes (if any). For our example data it is

    l$edges

    ##    V1 V2 label
    ## 1   2  1    ba
    ## 2   3  1    ca
    ## 3   4  1    da
    ## 4   5  1    ea
    ## 5   6  7    fg
    ## 6   8  9    hi
    ## 7  10 11    jk
    ## 8  11 12    kl
    ## 9  12 13    lm
    ## 10 13 14    mn
    ## 11 14 12    nl

The `vertexes` component contains data on vertexes with vertex id (the same that is used in the first two column of `edges`) is stored in the first two columns. The remaining columns store vertex attributes (if any). For our example data it is:

    l$vertexes

    ##    intergraph_id label
    ## 1              1     a
    ## 2              2     b
    ## 3              3     c
    ## 4              4     d
    ## 5              5     e
    ## 6              6     f
    ## 7              7     g
    ## 8              8     h
    ## 9              9     i
    ## 10            10     j
    ## 11            11     k
    ## 12            12     l
    ## 13            13     m
    ## 14            14     n
    ## 15            15     o

Functions `asNetwork` and `asIgraph` can also be used to create network objects from data frames such as those above. The first argument should be an edge list data frame. Optional argument `vertices` expectes data frames with vertex data (just like `l$vertexes`). Additionally we need to specify whether the edges should be interpreted as directed or not through the argument `directed`.

For example, to create an object of class “network” from the dataframes created above from object `exIgraph` we can:

    z <- asNetwork(l$edges, directed=TRUE, l$vertexes)
    z

    ##  Network attributes:
    ##   vertices = 15
    ##   directed = TRUE
    ##   hyper = FALSE
    ##   loops = FALSE
    ##   multiple = FALSE
    ##   bipartite = FALSE
    ##   total edges= 11
    ##     missing edges= 0
    ##     non-missing edges= 11
    ##
    ##  Vertex attribute names:
    ##     label vertex.names
    ##
    ##  Edge attribute names:
    ##     label

This is actually what basically happens when we call `asNetwork(exIgraph)`

# 4 Appendix

## 4.1 Example networks

Package intergraph contains four example networks:

- Objects `exNetwork` and `exIgraph` contain the same directed network as objects of class “network” and “igraph” respectively.
- Objects `exNetwork2` and `exIgraph2` contain the same undirected network as objects of class “network” and “igraph” respectively.

All four datasets contain:

- A vertex attribute `label` with vertex labels. These are letters from `a` to `o`.
- An edge attribute `label` with edge labels. These are pasted letters of the adjecent nodes.

We will use them in the examples below.

Networks are shown below using the following code:

    layout(matrix(1:4, 2, 2, byrow=TRUE))
    op <- par(mar=c(1,1,2,1))
    # compute layout
    coords <- layout.fruchterman.reingold(exIgraph)
    plot(exIgraph, main="exIgraph", layout=coords)
    plot(exIgraph2, main="exIgraph2", layout=coords)
    plot(exNetwork, main="exNetwork", displaylabels=TRUE, coord=coords)
    plot(exNetwork2, main="exNetwork2", displaylabels=TRUE, coord=coords)
    par(op)

## 4.2 Session information

    sessionInfo()

    ## R version 4.3.2 (2023-10-31)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 22.04.3 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
    ## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
    ##
    ## locale:
    ##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
    ##  [3] LC_TIME=pl_PL.UTF-8        LC_COLLATE=C
    ##  [5] LC_MONETARY=pl_PL.UTF-8    LC_MESSAGES=en_US.UTF-8
    ##  [7] LC_PAPER=pl_PL.UTF-8       LC_NAME=C
    ##  [9] LC_ADDRESS=C               LC_TELEPHONE=C
    ## [11] LC_MEASUREMENT=pl_PL.UTF-8 LC_IDENTIFICATION=C
    ##
    ## time zone: Europe/Warsaw
    ## tzcode source: system (glibc)
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] igraph_2.0.1.1   network_1.18.2   knitr_1.45       intergraph_2.0-4
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] crayon_1.5.2         vctrs_0.6.5          cli_3.6.2
    ##  [4] rlang_1.1.3          xfun_0.41            highr_0.10
    ##  [7] jsonlite_1.8.8       glue_1.7.0           htmltools_0.5.7
    ## [10] sass_0.4.8           fansi_1.0.6          rmarkdown_2.25
    ## [13] grid_4.3.2           evaluate_0.23        jquerylib_0.1.4
    ## [16] tibble_3.2.1         fastmap_1.1.1        yaml_2.3.8
    ## [19] lifecycle_1.0.4      compiler_4.3.2       coda_0.19-4
    ## [22] pkgconfig_2.0.3      statnet.common_4.9.0 lattice_0.22-5
    ## [25] digest_0.6.34        R6_2.5.1             utf8_1.2.4
    ## [28] pillar_1.9.0         magrittr_2.0.3       bslib_0.6.1
    ## [31] tools_4.3.2          cachem_1.0.8