igraph 中的子组件失败

subcomponent failed in igraph

我已经开始探索斯坦福大学的 Social Network Analysis 课程,在第二个实验室中,我遇到了提供的代码的问题。

它涉及以下功能:

reachability <- function(g, m) {
  reach_mat = matrix(nrow = vcount(g), 
                     ncol = vcount(g))
  for (i in 1:vcount(g)) {
    reach_mat[i,] = 0
    this_node_reach <- subcomponent(g, (i - 1), mode = m)

    for (j in 1:(length(this_node_reach))) {
      alter = this_node_reach[j] + 1
      reach_mat[i, alter] = 1
    }
  }
  return(reach_mat)
}

现在,当将此函数应用于具有以下特征的图形对象时krack_full

summary(krack_full)
 IGRAPH DN-- 21 232 -- 
 + attr: name (v/c), AGE (v/n), TENURE (v/n), LEVEL (v/n), DEPT (v/n), color (v/c), frame (v/c), advice_tie (e/n), friendship_tie (e/n),| reports_to_tie (e/n), color (e/c), arrow.size (e/n)

出现以下错误(通过回溯)

 Error in .Call("R_igraph_subcomponent", graph, as.igraph.vs(graph, v) -  : 
  At structural_properties.c:1244 : subcomponent failed, Invalid vertex id 
3 .Call("R_igraph_subcomponent", graph, as.igraph.vs(graph, v) - 
    1, as.numeric(mode), PACKAGE = "igraph") 
2 subcomponent(g, (i - 1), mode = m) 
1 reachability(krack_full, "in") 

你可以通过运行lab 1

得到准确的数据

知道如何解决这个错误吗?

您使用了错误的索引(R 索引从 1 开始),这应该是正确的:

reachability <- function(g, m) {
  reach_mat = matrix(nrow = vcount(g), 
                     ncol = vcount(g))
  for (i in 1:vcount(g)) {
    reach_mat[i,] = 0
    this_node_reach <- subcomponent(g, i, mode = m) # used "i" instead of "(i - 1)"

    for (j in 1:(length(this_node_reach))) {
      alter = this_node_reach[j] # removed "+ 1"
      reach_mat[i, alter] = 1
    }
  }
  return(reach_mat)
}

顺便说一句,我认为您可以获得相同的可达性矩阵:

# this returns the minimum distance between each node (=inf if not reachable)
distMatrix <- shortest.paths(krack_full, v=V(krack_full), to=V(krack_full))
# we set the values that are not infinite to 1
distMatrix[!is.infinite(distMatrix)] <- 1
# we set the values that are infinite to 0
distMatrix[is.infinite(distMatrix)] <- 0
# now distMatrix is your reachability matrix