Danielle
Danielle

Reputation: 339

Generate list of second-degree neighbors using lapply and igraph

I got some excellent advice here on how to lookup neighbors for a list of network nodes. See: lapply function to look up neighbors in igraph (when not all nodes are found)

Now I need to do the same thing with second-degree neighbors. However, substituting either ego or neighborhood function into this loop produces an error.

edgelist <- read.table(text = "
A B
B C
C D
D E
C F
F G")  

testlist <- read.table(text = "
A
H
C
D
J")  

testlist2 <- read.table(text = "
A
C
B
D
E") 

library(igraph)
graph <- graph.data.frame(edgelist)
str(graph)

get_neighbors <- function(graph, n) {

  do.call(rbind, lapply(n, function(x) {

    if (x %in% V(graph)$name) {

      nb <- neighborhood(graph,2, x)  ##HERE##

      if (length(nb) > 0) {
        data.frame(lookupnode=x,
                   neighbor=nb$name, # h/t @MrFlick for this shortcut
                   stringsAsFactors=FALSE)
      } else {
        data.frame(lookupnode=x, neighbor=NA, stringsAsFactors=FALSE)
      }

    } else {  
      data.frame(lookupnode=x, neighbor=NA, stringsAsFactors=FALSE)
    }

  }))

}

A=get_neighbors(graph, as.character(testlist$V1))

Error in data.frame(lookupnode = x, neighbor = nb$name, stringsAsFactors = FALSE) : arguments imply differing number of rows: 1, 0

I gather the issue is that ego and neighborhood can't be directly coerced into a data frame. I can use unlist and then put in a data frame, but the values I want end up as row.names not values that I can put into my output.

How can I create an output of second-degree neighbors?

Upvotes: 3

Views: 667

Answers (1)

Rohit Das
Rohit Das

Reputation: 2032

Changed

neighbor=nb$name, # h/t @MrFlick for this shortcut

to

neighbor=names(unlist(nb)), # h/t @MrFlick for this shortcut

and it is working for me now.

> A
   lookupnode neighbor
1           A        A
2           A        B
3           A        C
4           H     <NA>
5           C        C
6           C        B
7           C        D
8           C        F
9           C        A
10          C        E
11          C        G
12          D        D
13          D        C
14          D        E
15          D        B
16          D        F
17          J     <NA>
> 

Upvotes: 2

Related Questions