简体   繁体   中英

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

how do I count the number of friends of student "G" in subgraph "subschool"?

One way could be

sum(schoolgraph["G",V(schoolsub)$name])
# [1] 2

or

slam::row_sums(schoolgraph[c("F", "G"),V(schoolsub)$name])
# F G 
# 2 2

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"

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