如何为网络创建度相关矩阵

3
我想为一个网络创建一个度相关性矩阵,其中列和行捕捉网络的度数。我不是在寻找全局度量-像assortativity_degree()那样,而是实际上是一个相关矩阵,其中矩阵中的每个元素都是图形中存在的边缘数量,其节点的度数=任何内容和度数=任何内容。我已经在igraph文档和谷歌上搜索过了,但没有找到我想要的东西。我拼凑出了以下内容,似乎可以工作,但我想知道是否有更简单的方法,我很无知。我认为我想要的东西并不是那么神秘,没有人考虑过它-也许在igraph或类似的函数中有一个函数,我只是不太知道它的名称。
library(igraph)
#> 
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:stats':
#> 
#>     decompose, spectrum
#> The following object is masked from 'package:base':
#> 
#>     union

g <- make_graph("Zachary")

x <- sort(unique(degree(g))) # vector of all degrees in the network
y <- sort(unique(degree(g))) # vector for all degrees in the network

datalist = list()

# this loop creates a vector that identifies the number of 
# edges that occur between nodes of degree whatever and degree whatever
for(i in y) {               
 row <- mapply(function(x) 
 {length(E(g)[V(g)[degree(g) == i] %--% V(g)[degree(g) == x]])},
 x)      
 datalist[[i]] <- row 
}

# takes the data list created in the previous for loop and row bind it into a 
# matrix
m = do.call(rbind, datalist)

# label rows and columns with the relevatn degree
rownames(m) <- unique(sort(degree(g)))
colnames(m) <- unique(sort(degree(g)))

m
#>    1 2 3 4 5 6 9 10 12 16 17
#> 1  0 0 0 0 0 0 0  0  0  1  0
#> 2  0 0 0 3 0 1 2  1  5  3  7
#> 3  0 0 2 3 1 3 1  1  0  3  2
#> 4  0 3 3 1 3 1 2  2  2  3  3
#> 5  0 0 1 3 0 1 1  2  2  2  3
#> 6  0 1 3 1 1 0 1  1  1  2  1
#> 9  0 2 1 2 1 1 0  1  0  1  0
#> 10 0 1 1 2 2 1 1  0  1  1  0
#> 12 0 5 0 2 2 1 0  1  0  0  1
#> 16 1 3 3 3 2 2 1  1  0  0  0
#> 17 0 7 2 3 3 1 0  0  1  0  0

这段文本是由 reprex包(v2.0.0)创建于2021年6月19日。

1个回答

3
我们可以通过创建度数图来实现类似以下的操作,即 g.dg
dg <- degree(g)
g.dg <- graph_from_data_frame(
    with(
        get.data.frame(g),
        data.frame(dg[from], dg[to])
    ),
    directed = FALSE
)
mat <- get.adjacency(g.dg, sparse = FALSE)
ord <- order(as.numeric(row.names(mat)))
out <- mat[ord, ord]

它提供的是

   1 2 3 4 5 6 9 10 12 16 17
1  0 0 0 0 0 0 0  0  0  1  0
2  0 0 0 3 0 1 2  1  5  3  7
3  0 0 2 3 1 3 1  1  0  3  2
4  0 3 3 1 3 1 2  2  2  3  3
5  0 0 1 3 0 1 1  2  2  2  3
6  0 1 3 1 1 0 1  1  1  2  1
9  0 2 1 2 1 1 0  1  0  1  0
10 0 1 1 2 2 1 1  0  1  1  0
12 0 5 0 2 2 1 0  1  0  0  1
16 1 3 3 3 2 2 1  1  0  0  0
17 0 7 2 3 3 1 0  0  1  0  0

这真是太棒了。谢谢你。你能解释一下with()函数内部发生了什么吗?我看到它将data.frame函数应用于图的边缘列表,但从概念上讲,我无法弄清楚它具体做了什么。 - undefined
@avgoustisw 你看到get.data.frame(g)有两列,fromto。使用with,我们进入了get.data.frame(g)的环境,并且可以将fromto作为数据的名称(而不是get.data.frame(g)$fromget.data.frame(g)$to)。如果你输入?with,你会看到更多的例子和解释。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接