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.
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 sort
ing the result to get an ordered list, from most to least connected ( decreasing=TRUE
).
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 by result$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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.