lapply 在 igraph 中查找邻居的函数(当未找到所有节点时)

lapply function to look up neighbors in igraph (when not all nodes are found)

我正在尝试为节点列表创建一个网络邻居数据集。我虽然可以通过使用 neighbors 命令的 lapply 函数来做到这一点。作为一个额外的并发症,我的一些查找节点不在图中,但无论如何我都无法让它工作。

这是一个例子:

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)

neighbors<- lapply(testlist2, function(p) {  #Each pledge_id
  temp=neighbors(graph,p)  #Find all the neighbors for that pledge 
  return(temp)
})

neighbors<- lapply(testlist, function(p) {  #Each pledge_id
  temp=neighbors(graph,p)  #Find all the neighbors for that pledge 
  return(temp)
})

不幸的是,这 returns 两种情况都是废话。我错过了什么?

我想要的输出是这样的:

lookupnode neighbor
A    B
H    .
C    D
C    F
D    E
J    .

我知道最终我需要在某处添加一个 temp=data.table::rbindlist(temp) 命令,但我不认为这是造成废话的原因。

一件事是您正在使用 read.table 函数创建一个 data.frame 并将该 data.frame 传递给 lapply 因此它会遍历每个向量,不是 data.frame.

V1 向量的元素

其次,V1 列是一个因子(h/t @Psidom 的因子提示)。

第三,neighbors() 函数将 return 需要迭代的图形顶点(根据我的计算)并具有 name 属性 returned .

然后,正如您所建议的,这些需要 rbinded 成 data.frame:

get_neighbors <- function(graph, n) {

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

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

      nb <- neighbors(graph, x)

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

  }))

}

get_neighbors(graph, as.character(testlist$V1))
##   lookupnode neighbor
## 1          A        B
## 2          H     <NA>
## 3          C        D
## 4          C        F
## 5          D        E
## 6          J     <NA>

get_neighbors(graph, as.character(testlist2$V1))
##   lookupnode neighbor
## 1          A        B
## 2          C        D
## 3          C        F
## 4          B        C
## 5          D        E
## 6          E     <NA>

不知道Gabor能不能在C端向量化neighbors()

更新:

ego 解决方案只是稍有不同:

get_ego <- function(g, v, n=2) {
  do.call(rbind, lapply(v, function(x) {
    if (x %in% V(g)$name) {
      data.frame(node=x,
                 ego_n=sapply(ego(g, n, x), function(y) { V(g)[y]$name }),
                 stringsAsFactors=FALSE)
    } else {
      data.frame(node=x, ego_n=NA, stringsAsFactors=FALSE)
    }
  }))
}