I have an undirected graph and could categorise them into three categories (Gg, Sg, Eg). I want to list the neighbours of all the nodes from Eg category to Gg&Sg categories. What is the best way to do it?
I tried to approach it like below:
set.seed(123)
# Generate graph and node attribute
g <- sample_gnp(25, 2/10)
V(g)$name <- LETTERS[seq_len(gorder(g))]
V(g)$nCat <- sample(c("Gg", "Sg", "Eg"), 25, replace = TRUE)
vertex.attributes(g) %>% as_tibble() %>% filter(nCat == "Eg")
# # A tibble: 10 x 2
# name nCat
# <chr> <chr>
# 1 B Eg
# 2 C Eg
# 3 F Eg
# 4 H Eg
# 5 L Eg
# 6 O Eg
# 7 P Eg
# 8 Q Eg
# 9 W Eg
# 10 X Eg
# Fetch the adjacency list
get.adjlist(g) %>% head(3)
# $A
# + 4/25 vertices, named, from 9d72dda:
# [1] L R W Y
#
# $B
# + 4/25 vertices, named, from 9d72dda:
# [1] G K P T
#
# $C
# + 3/25 vertices, named, from 9d72dda:
# [1] D G N
# ...
Expected output (dataframe):
# col1 col2
# B G
# B K
# B P
# B T
# C D
# C G
# C N
# ...
Are there any better approaches?
Maybe like this?
get.edgelist(g) %>% as_tibble() %>% filter(V1 %in% c("B", "C"))
# A tibble: 7 x 2
# V1 V2
# <chr> <chr>
# 1 C D
# 2 B G
# 3 C G
# 4 B K
# 5 C N
# 6 B P
# 7 B T
For these two nodes, it is fine. But when I looked for more nodes, I found that this might not be the right approach as the order of the nodes for an edge does not matter (i.e., A-B and B-A are the same).
get.edgelist(g) %>% as_tibble() %>% group_by(V1) %>% add_count() %>% distinct(V1, n) %>% arrange(V1)
# A tibble: 22 x 2
# Groups: V1 [22]
# V1 n
# <chr> <int>
# 1 A 4
# 2 B 4
# 3 C 3
# 4 D 4
# 5 E 4
# 6 F 1
# 7 G 3
# 8 H 7
# 9 I 2
# 10 J 3
# # ... with 12 more rows
get.adjlist(g)
# $A
# + 4/25 vertices, named, from 9d72dda:
# [1] L R W Y
#
# $B
# + 4/25 vertices, named, from 9d72dda:
# [1] G K P T
#
# $C
# + 3/25 vertices, named, from 9d72dda:
# [1] D G N
#
# $D
# + 5/25 vertices, named, from 9d72dda:
# [1] C O R S T
#
# $O
# + 4/25 vertices, named, from 9d72dda:
# [1] D F J T
#
#
# $R
# + 7/25 vertices, named, from 9d72dda:
# [1] A D G H M P S
#
# $S
# + 4/25 vertices, named, from 9d72dda:
# [1] D M R Y
#
# $T
# + 5/25 vertices, named, from 9d72dda:
# [1] B D O X Y
get.edgelist(g) %>% as_tibble() %>% group_by(V1) %>% add_count() %>% distinct(V1, n) %>%
filter(V1 %in% c("A", "B", "C", "D", "O", "R", "S", "T")) %>% arrange(V1)
# A tibble: 8 x 2
# Groups: V1 [8]
# V1 n
# <chr> <int>
# 1 A 4
# 2 B 4
# 3 C 3
# 4 D 4
# 5 O 1
# 6 R 1
# 7 S 1
# 8 T 2
Thanks for looking into this request.