【问题标题】:Deleting a single node in R删除 R 中的单个节点
【发布时间】:2014-12-09 05:36:21
【问题描述】:

我正在尝试使用 R 可视化产品的优惠网络。我已经使用 igraph 绘制了产品网络图,但我想看看如果我要删除一个产品会发生什么。我发现我可以使用

删除一个节点
g2 <- g - V(g)[15]

但它也会删除连接到该特定节点的所有边。

有什么方法可以只删除一个节点,并查看删除该节点后其他节点如何重新连接?对此问题的任何帮助表示赞赏。

附言

希望这会让它更清楚:

例如,如果我们生成随机图:

set.seed(10)
Data <- data.frame(
  X = sample(1:10),
  Y = sample(3, 10, replace=T)
)
d <- graph.data.frame(Data)
plot(d)
d2 <- d-V(d)[2] #deleting '3' from the network
plot(d2)

如果您注意到,当您从网络中删除节点“3”时,节点“9”仍然处于未连接状态。连接节点“3”后,有没有办法查看节点“9”的新边?仍然遵循相同的情节,我们预计它将连接到节点“2”。在 igraph 中是否有执行此操作的功能?还是我应该为它编写代码?

【问题讨论】:

  • 你能发一个more representative example吗?或者至少,更清楚地显示问题(例如,通过添加带有初始图和最终所需图的图像的示例)
  • “删除一个节点后,其他节点如何重新连接”他们假设如何重新连接?
  • @digEmAll 哦,好的,我稍后会放一个。
  • @m0nhawk 举个例子,这样会更清楚一点
  • 如果你有 A -> B C 相同。我猜对于无向图来说更容易。

标签: r networking igraph


【解决方案1】:

也许不是最有效的方法,但应该可以:

library(igraph)

set.seed(10) # for plot images reproducibility

# create a graph
df <- data.frame(
  X = c('A','A','B','B','D','E'),
  Y = c('B','C','C','F','B','B')
)
d <- graph.data.frame(df)

# plot the original graph
plot(d)

# function to remove the vertex
removeVertexAndKeepConnections <- function(g,v){

  # we does not support multiple vertices
  stopifnot(length(v) == 1)

  vert2rem <- V(g)[v]

  if(is.directed(g) == FALSE){
    # get the neigbors of the vertex to remove
    vx <- as.integer(V(g)[nei(vert2rem)])
    # create edges to add before vertex removal
    newEdges <- as.matrix(unique(expand.grid(vx,vx)))
    # remove the cycles
    newEdges <- newEdges[newEdges[,1] != newEdges[,2],]
    # sort each row index to remove all the duplicates
    newEdges <- t(apply(newEdges,1,sort))
    newEdges <- unique(newEdges)
  }else{
    # get the ingoing/outgoing neigbors of the vertex to remove
    vx <- as.integer(V(g)[nei(vert2rem,mode='in')])
    vy <- as.integer(V(g)[nei(vert2rem,mode='out')])
    # create edges to add before vertex removal
    newEdges <- as.matrix(unique(expand.grid(vx,vy)))
  }

  # remove already existing edges
  newEdges <- newEdges[!apply(newEdges,MARGIN=1,FUN=function(x)are.connected(g,x[1],x[2])),]

  # add the edges
  g <- g + edges(as.integer(t(newEdges)))
  # remove the vertex
  g <- g - vertex(vert2rem)

  return(g)
}

# let's remove B (you can also use the index
v <- 'B'
plot(removeVertexAndKeepConnections(d,v))

原文:

修改:

【讨论】:

  • 已编辑:增加了对无向图的支持
  • 太棒了!这很有帮助!谢谢!
  • @basecracker:为无向图添加了一个小错误修复
猜你喜欢
  • 1970-01-01
  • 2010-12-29
  • 2015-05-24
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多