简体   繁体   English

igraph包中的子图错误

[英]Error with subgraph in igraph package

I want to get the subgraph of all the cycles in a graph. 我想获得图中所有周期的子图。 I tried the code below 我尝试了下面的代码

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

But it throws and error as below: 但是它会抛出如下错误:

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

I found that the code works with the second element in the cycles list which is shorter but not the first one. 我发现代码与cycles列表中的第二个元素一起使用,该元素较短,但第一个元素不是。 So if I try this will work, 因此,如果我尝试这样做会起作用,

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

but not 但不是

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

Also, any suggestions to substitute the for loop are welcomed. 同样,欢迎提出任何替代for循环的建议。

A reproducible example: 一个可重现的示例:

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

If you pass a number as a vertex id to the induced.subgraph function, it will be accessing the vertices by number (in your graph numbers 1 through 23), leading to the "Invalid vertex ID" error due to indices like 26, 29, and 30. You want to actually refer to vertices by name, which you can do by passing a string instead of a number: 如果您将一个数字作为顶点ID传递给induced.subgraph函数,它将按数字访问顶点(在您的图形编号1到23中),由于诸如26、29之类的索引而导致“无效顶点ID”错误和30。您实际上想按名称引用顶点,可以通过传递字符串而不是数字来实现:

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

Now you have successfully extracted the two subgraphs: 现在,您已经成功提取了两个子图:

在此处输入图片说明

在这里输入代码

There's no way to avoid looping through your list to generate the subgraphs, though you could hide the loop with something like the lapply function: 尽管可以使用lapply函数之类的lapply隐藏循环,但无法避免循环遍历列表以生成子图:

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

Now subgraphs is a list of graphs, one for each cycle. 现在, subgraphs是一个图列表,每个循环一个。 They can be accessed with subgraphs[[1]] and subgraphs[[2]] in your case. 您可以使用subgraphs[[1]]subgraphs[[2]]访问它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM