Search code examples
rmatrixedgessnaedge-list

How to calculate the number of edges between nodes of a certain group?


I have the following dataset and the following script:

library(GGally)
library(ggnet)
library(network)
library(sna)
library(ggplot2)

# edgelist
e <- data.frame(sender = c(1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5),
                receiver = c(2, 3, 4, 5, 1, 3, 1, 1, 2, 2, 4, 3, 2, 4))

# information about the nodes (vertices)
v <- data.frame(actors = c(1, 2, 3, 4, 5),
                groups = c("A", "A", "B", "C", "D"))

net <- network(e, directed = TRUE)

x = data.frame(actors = network.vertex.names(net))
x = merge(x, v, by = "actors", sort = FALSE)$groups

net %v% "group" = as.character(x)

y = RColorBrewer::brewer.pal(9, "Set1")[ c(3, 1, 9, 6, 8) ]
names(y) = levels(x)

ggnet2(net, color = "group", palette = y, alpha = 0.75, size = 4, edge.alpha = 0.5, arrow.size = 8, arrow.gap = 0.01)

Is there an easy and fast way to calculate the number of edges from group of nodes (A, B, C, D) to the same group of nodes or to another group of nodes (i.e., from A-A, A-B, A-C, A-D, B-A, etc.)?

There is network.edgecountin the network-Package. But how can I apply it to my question?


Solution

  • The mixingmatrix function from network does the trick. It displays the number of ties within and between groups, getting at homophily and assortive mixing.

    > mixingmatrix(net, "group")
           To
    From    A B C D Total
      A     3 2 1 1     7
      B     3 0 1 0     4
      C     1 1 0 0     2
      D     0 0 1 0     1
      Total 7 3 3 1    14