2015-05-12 39 views
1

我想要得到圖中所有周期的子圖。我想下面igraph包中的子圖出錯

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

回答

4

如果傳遞一個數字作爲一個頂點ID爲induced.subgraph功能,將訪問由若干頂點(在圖形中數字1到23),導致「無效的頂點ID」錯誤,由於像26指數,29和30。你想傳遞一個字符串而不是數按名稱實際上是指頂點,你可以這樣做:

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

現在你有成功提取了兩個子圖:

enter image description here

enter code here

有沒有辦法避免以列表循環,從而生成子圖,雖然你可以隱藏環路的東西像lapply功能:

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

現在subgraphs是一個圖表列表,每個循環一個圖表。他們可以通過subgraphs[[1]]subgraphs[[2]]進行訪問。