我有下面的网络图:

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)

enter image description here

我学会了如何删除这个图表中的所有"边":

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

现在,我try 做同样的事情,但使用"循环"代替:

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创建

R相关问答推荐

将Multilinetring合并到一个线串中,使用sf生成规则间隔的点

单击 map 后,将坐标复制到剪贴板

从嵌套列表中智能提取线性模型系数

R Markdown中的交叉引用表

从gtsummary包中使用tBL_strata()和tBL_summary()时删除变量标签

判断字符串中数字的连续性

derrr summarise每个组返回多行?

我不能在docker中加载sf

根据多个条件增加y轴高度以适应geom_text标签

如何从R ggplot图片中获取SVG字符串?

plotly hover文本/工具提示在shiny 中不起作用

为什么我使用geom_density的绘图不能到达x轴?

R -使用矩阵reshape 列表

手动指定从相同数据创建的叠加图的 colored颜色

为什么我对圆周率图的蒙特卡罗估计是空的?

在ggploy中创建GeV分布时出错

R预测包如何处理ARIMA(Auto.arima函数)中的缺失值

如何修改GT表中组名行的 colored颜色 ?

将CSV转换为R中的自定义JSON格式

根据向量对列表元素进行排序