简体   繁体   中英

Calculate degree of a subgraph using r igraph

I know the degree of my global graph, but now I need to find the degrees of nodes within a subgraph. So, John has 4 friends in his school, but three friends in his class. How do I instruct igraph to count those three friends in his class, but not the rest in his school?

My global graph

library(igraph)
school <- read.table(text="
    A   B   C   D   E   F   G
A   0   1   0   1   0   1   1
B   1   0   1   1   0   1   0
C   0   0   0   0   0   0   1
D   1   1   0   0   1   0   0
E   0   0   0   1   0   1   1
F   0   1   0   0   1   0   1
G   1   0   1   0   1   1   0", header=TRUE)

mat <- as.matrix(school)
g <- graph.adjacency(mat, mode="undirected", add.rownames = T)

My affiliation matrix for classes P, Q, and R

x <- read.table(text="
                    P   Q   R
                A   1   1   0
                B   0   0   1
                C   0   0   0
                D   1   0   1
                E   1   1   0
                F   0   1   0
                G   1   1   1", header=TRUE)

inc <- as.matrix(x)
ginc <- graph.incidence(inc)

My subgraph for class P

class_nodes <- names(which(inc[,"P"] == 1))
class_adj   <- mat[class_nodes, class_nodes]
class_graph <- graph.adjacency(class_adj, mode = "undirected")

I need to calculate the degree of nodes in subgraph "class_graph", but counting only their ties within the subgraph, not the global graph.

You can find all the nodes in class P with (we specifically extract the names so we can look them up in a different graph object).

V(ginc)[.nei("P")]$name

Then you can extract just that subset of connections from the main graph with

subg <- induced.subgraph(g, V(ginc)[.nei("P")]$name)

and you can calculate the degree of those nodes with

degree(subg)
# A D E G 
# 2 2 2 2

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