我已经开始探索斯坦福大学的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
来获取准确的数据知道如何修复此错误吗?
答案 0 :(得分: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)
}
BTW,我认为你可以通过以下方式获得相同的可达性矩阵:
# 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