Reputation: 905
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).
Upvotes: 0
Views: 168
Reputation: 24188
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"
Upvotes: 1
Reputation: 54237
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
Upvotes: 2