在循环中覆盖 "Non-Existent Components"

Overriding "Non-Existent Components" in a Loop

我有以下网络图:

library(tidyverse)
library(igraph)


set.seed(123)
n=15
data = tibble(d = paste(1:n))

relations = tibble(
  from = sample(data$d),
  to = lead(from, default=from[1]),
)

graph = graph_from_data_frame(relations, directed=T, vertices = data) 

V(graph)$color <- ifelse(data$d == relations$from[1], "red", "orange")

plot(graph, layout=layout.circle, edge.arrow.size = 0.2)

我学会了如何删除这张图中的所有“边”:

g <- graph-E(graph)
plot(g)

现在,我正在尝试做同样的事情,但使用的是“循环”:

for (i in 1:15)
 for (j in 1:15) { 

graph <- graph - edge(paste0(i, "|", j)) 

} 

但我认为问题是上面的代码试图删除存在的“边缘”,而这段代码没有能力在命令删除非实例时“跳过”(覆盖)实例-现有边:

Error in delete_edges(e1, unlist(e2, recursive = FALSE)) : 
  At iterators.c:1828 : Cannot create iterator, invalid edge id, Invalid vertex id

有没有办法指示这个“循环”“跳过”两条边没有连接的每个实例并继续直到循环完成?

谢谢!

我不知道你为什么要 运行 一个 for 循环,但请使用 igraph 库中的 as_edgelist() 函数在下面找到可能的解决方案.

Reprex

  • 您的数据
library(igraph)
library(dplyr)

set.seed(123)
n=15
data = tibble(d = paste(1:n))

relations = tibble(
  from = sample(data$d),
  to = lead(from, default=from[1]),
)

graph = graph_from_data_frame(relations, directed=T, vertices = data) 

V(graph)$color <- ifelse(data$d == relations$from[1], "red", "orange")

plot(graph, layout=layout.circle, edge.arrow.size = 0.2)

  • 建议代码
edgelist <- as_edgelist(graph, names = TRUE)

  for (i in 1:15) { 
    
    graph <- graph - edge(paste0(edgelist[i,1], "|", edgelist[i,2])) 
    
  } 

plot(graph)

reprex package (v2.0.1)

于 2022-02-24 创建