Search code examples
rigraphsubgraph

r igraph - Identify ties of nodes to a subgraph regardless of affiliation to said subgraph


How to count the ties of a node to a subgraph of the same graph? In a school context, how to count student G's friends in a specific class, regardless of her belonging there?

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)
schoolgraph <- graph.adjacency(mat, mode="undirected", add.rownames = T)

My subgraph

schoolsub <- induced.subgraph(schoolgraph,1:3)

IGRAPH 7dfb160 UN-- 3 2 -- 
+ attr: name (v/c), TRUE (v/c)
+ edges from 7dfb160 (vertex names):
[1] A--B B--C

Now, how do I count the number of friends of student "G" in subgraph "subschool"? The results should be a number (G has two friends in schoolsub) and a list of names (G is friends with A and C of schoolsub).


Solution

  • You can get the neighbours first, and use them to subset schoolsub:

    nbs <- neighbors(schoolgraph, "G")$name
    V(schoolsub)$name[V(schoolsub)$name %in% nbs]
    #[1] "A" "C"