简体   繁体   中英

Compute degree of each vertex from data frame

I have the following dataset:

V1 V2
 2 1
 3 1
 3 2
 4 1
 4 2
 4 3
 5 1
 6 1
 7 1
 7 5
 7 6

I tried to compute the degree of each vertex with the code

e<-read.table("ex.txt")
library(igraph)
g1<-graph.data.frame(e, directed=FALSE)
adj<- get.adjacency(g1,type=c("both", "upper", "lower"),attr=NULL, names=TRUE, sparse=FALSE)
d<-rowSums(adj)
e$degreeOfV1<-d[e$V1]
e$degofV2<-d[e$V2]

the degree given by this code is not correct.

The problem with this code is that the nodes have be inputted into your graph in a different order than you expected:

V(g1)
# + 7/7 vertices, named:
# [1] 2 3 4 5 6 7 1

The first node in the graph (corresponding to element 1 of your d object) is actually node number 2 in e , element 2 is node number 3 in e , etc.

You can deal with this by using the node names instead of the node numbers when calculating the degrees:

d <- degree(g1)
e$degreeOfV1 <- d[as.character(e$V1)]
e$degreeOfV2 <- d[as.character(e$V2)]
#    V1 V2 degreeOfV1 degreeOfV2
# 1   2  1          3          6
# 2   3  1          3          6
# 3   3  2          3          3
# 4   4  1          3          6
# 5   4  2          3          3
# 6   4  3          3          3
# 7   5  1          2          6
# 8   6  1          2          6
# 9   7  1          3          6
# 10  7  5          3          2
# 11  7  6          3          2

Basically the way this works is that degree(g1) returns a named vector of the degrees of each node in your graph:

(d <- degree(g1))
# 2 3 4 5 6 7 1 
# 3 3 3 2 2 3 6 

When you index by strings ( as.character(e$V1) instead of e$V1 ), then you get the node by name instead of by index number.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM