Timothée HENRY
Timothée HENRY

Reputation: 14604

r igraph most connected nodes

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.

enter image description here

Upvotes: 1

Views: 1872

Answers (3)

Jota
Jota

Reputation: 17611

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

Upvotes: 1

Conta
Conta

Reputation: 585

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

Upvotes: 1

arvi1000
arvi1000

Reputation: 9582

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).

Upvotes: 2

Related Questions