Extract names of neighbour of a collection of nodes as list

Viewed 68

I want to extract the names of the neighbors of selected nodes in igraph as a list.

This is what I have so far:

library(igraph)
set.seed(100)
g<-erdos.renyi.game(26, 0.4)
V(g)$name<-letters
x<-neighborhood(g, order = 1, V(g)$name %in% c('a', 'd', 'z'))

In the above example, I want to extract the names of the neighbours of nodes a,d, and z. And this is the output I am getting:

[[1]]
+ 9/26 vertices, named, from 6ba7060:
[1] a c h i l q w x z

[[2]]
+ 11/26 vertices, named, from 6ba7060:
 [1] d b c e g h i k l w y

[[3]]
+ 9/26 vertices, named, from 6ba7060:
[1] z a c g h l o u v

I want to make a long list of the names with representations. The output should look like:

[1] "a" "c" "h" "i" "l" "q" "w" "x" "z" "d" "b" "c" "e" "g" "h" "i" "k" "l" "w" "y" "z" "a" "c"
[24] "g" "h" "l" "o" "u" "v

Thus far I have tried unlist and various versions of x %>% map(2) %>% flatten() using the library purrr, but to no avail.

I am also not oppose to getting the output in the form of a data.frame or tibble with names in one column and count of occurrences in another.

3 Answers

You can apply names() to each elements in the list to get the vertex name as a character value, and then you can unlist those lists into a single character vector

unlist(lapply(x, names))

Maybe you can try names(unlist(x)), e.g.,

> names(unlist(x))
 [1] "a" "c" "h" "i" "l" "q" "w" "x" "z" "d" "b" "c" "e" "g" "h" "i" "k" "l" "w"
[20] "y" "z" "a" "c" "g" "h" "l" "o" "u" "v"

If you would rather a data frame with counts, you can do:

stack(table(unlist(lapply(x, names))))[2:1]
#>    ind values
#> 1    a      2
#> 2    b      1
#> 3    c      3
#> 4    d      1
#> 5    e      1
#> 6    g      2
#> 7    h      3
#> 8    i      2
#> 9    k      1
#> 10   l      3
#> 11   o      1
#> 12   q      1
#> 13   u      1
#> 14   v      1
#> 15   w      2
#> 16   x      1
#> 17   y      1
#> 18   z      2
Related