我有以下网络图:
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 于 2022 年 2 月 24 日创建(v2.0.1)
关于r - 在循环中覆盖 "Non-Existent Components",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71255038/