igraph 包中的子图出错

Error with subgraph in igraph package

我想得到图中所有循环的子图。我尝试了下面的代码

 for (i in 1:length(cycles)){
    vids<-as.numeric(unlist(cycles[[i]]))
    subgraph<- induced.subgraph(graph, vids)
 }

但它抛出如下错误:

Error in .Call("R_igraph_induced_subgraph", graph, vids - 1, impl, PACKAGE = "igraph") : 
  At iterators.c:759 : Cannot create iterator, invalid vertex id, Invalid vertex id

我发现该代码适用于 cycles 列表中的第二个元素,该列表较短,但不适用于第一个元素。 因此,如果我尝试这样做会奏效,

subgraph<- induced.subgraph(g, c(3,4))

但不是

subgraph<- induced.subgraph(g, c(26, 2, 30, 29, 25, 9, 27, 13, 14, 8, 23, 20, 19, 17, 12, 11, 24, 21, 6, 28, 15,3,4))

此外,欢迎任何替代 for 循环的建议。

一个可重现的例子:

    library(igraph)
    graph<-graph(c(1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,14,14,15,15,16,
           16,17,17,18,18,19,19,20,20,21,21,1,22,23,23,22),directed=T)
    V(graph)$name<-c(26, 2, 30, 29, 25, 9, 27, 13, 14, 8, 23, 20, 19, 17, 12, 11, 
             24, 21, 6, 28, 15,3,4)

    cycles<-list(list(26L, 2L, 30L, 29L, 25L, 9L, 27L, 13L, 14L, 8L, 23L, 
        20L, 19L, 17L, 12L, 11L, 24L, 21L, 6L, 28L, 15L), list(4L, 
        3L))

如果您将一个数字作为顶点 ID 传递给 induced.subgraph 函数,它将按数字访问顶点(在您的图形编号 1 到 23 中),导致 "Invalid vertex ID" 错误由于像 26、29 和 30 这样的索引。你想按名称实际引用顶点,你可以通过传递字符串而不是数字来实现:

for (i in 1:length(cycles)){
  vids <- as.character(unlist(cycles[[i]]))
  subgraph<- induced.subgraph(graph, vids)
  plot(subgraph)
}

现在你已经成功提取了两个子图:

无法避免循环遍历您的列表以生成子图,尽管您可以使用类似 lapply 函数的东西来隐藏循环:

subgraphs <- lapply(cycles, function(x) induced.subgraph(graph, as.character(unlist(x))))

现在subgraphs是图表列表,每个周期一个。在您的情况下,可以使用 subgraphs[[1]]subgraphs[[2]] 访问它们。