r igraph most connected nodes

大兔子大兔子 提交于 2019-12-13 02:26:35

问题


I have a graph:

paths = data.frame(from=c(10,20,30,10,30), to=c(20,30,50,30,60))
g <- graph_from_data_frame(paths, directed=FALSE)
plot(g)

Is there a command to find out the number of connections of each node, and find the most connected node. In this example 30 is the most connected node, with 4 connections. Then come 20 and 10 with 2 connections each.


回答1:


In this case you can just calculate it from the data.frame, by counting number of connections (treating from & to as the same, since the appearance of a node in either vector means 1 connection):

sort(table(c(paths$from, paths$to)), decreasing = TRUE)

Result:

30 10 20 50 60 
 4  2  2  1  1 

Explanation: The code is creating a vector of all connections (c(paths$from, paths$to)), then counting frequency (table), then sorting the result to get an ordered list, from most to least connected (decreasing=TRUE).




回答2:


Here to find number of connections, you just need to count the appearance of each number in the data.frame, for example, 10 appears twice, the number of connection is 2. You can use rle, which returns an object with two attributes:

result <- rle(sort(c(paths[,1], paths[,2])))

> result
Run Length Encoding
lengths: int [1:5] 2 2 4 1 1
values : num [1:5] 10 20 30 50 60

And you can get its count byresult$values, also you could make the result into a data.frame:

> data.frame(dot=result$lengths, count=result$values)
  dot count
1   2    10
2   2    20
3   4    30
4   1    50
5   1    60



回答3:


Try this

lengths(as_adj_list(g))
# 10 20 30 50 60 
#  2  2  4  1  1 

Or try this using the colSums function from Matrix:

library(Matrix)
colSums(g[])
# 10 20 30 50 60 
#  2  2  4  1  1

which.max(colSums(g[]))
# 30 
#  3 

max(colSums(g[]))
# [1] 4


来源:https://stackoverflow.com/questions/34799702/r-igraph-most-connected-nodes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!