【问题标题】:Netting a weighted matrix in igraph (R)在 igraph (R) 中计算加权矩阵
【发布时间】:2015-08-10 13:56:08
【问题描述】:

是否有一种我缺少的简单方法可以在 igraph 中创建一个简单、加权、有向网络的网状版本?这是相互边缘被替换为带有权重之间差异的单个边缘的地方,并且方向使得权重始终为正。一个简单的例子:

gGross <- graph_from_literal(A++B)
E(gGross)$weight <- c(12, 20)

gNet <- graph_from_literal(A+-B)
E(gNet)$weight <- c(8)

在矩阵表示法中,这将是

N_{ij} = (A_{ij} - A_{ji})_+

+ 表示保留积极的元素。

一个好的起点是类似于which_mutual 的东西,它给出了返回边缘的索引。我可以想象在 R 中编写一个长函数,但这似乎很慢。

【问题讨论】:

  • 我在最后一点上取得了一些进展。 ends(g, E(g)[which_mutual(g)], names=FALSE) 给出所有相互边的矩阵。这可以输入到应用程序中。
  • 这几乎是我需要的 g2 &lt;- as.undirected(g, mode="collapse", edge.attr.comb = function(x) x[1]-x[2]) 但不确定方向的可靠性。

标签: r igraph


【解决方案1】:

我觉得我可以做得比这更好,但我至少有一个工作方法。最欢迎改进。编辑以反映 Tamás 的 cmets 并允许使用任何属性

nettedGraph <- function(g, col="weight") {

  if(!(col %in% edge_attr_names(g))) {
    stop(col, " not and edge attribute")
  }

  # Get a matrix of mutual edges (by vertex ids)
  me <- ends(g, E(g)[which_mutual(g)], names=FALSE)

  # Only keep one of the mutual edges
  me <- me[me[,1] < me[,2], ] 

  toDel <- vector(mode="integer", length=nrow(me))

  for (i in 1:nrow(me)) {

    # Get edge ids going each way
    e1 <- get.edge.ids(g, c(me[i,1],me[i,2]))
    e2 <- get.edge.ids(g, c(me[i,2],me[i,1]))

    weightDiff <- edge_attr(g,col, e1) - edge_attr(g,col, e2)

    if(weightDiff > 0) {
      # Update the edge we're keeping
      edge_attr(g,col, e1) <- weightDiff
      # Delete the one we're not
      toDel[i] <- e2
    } else {
      # Update the edge we're keeping
      edge_attr(g,col, e2) <- -weightDiff
      # Delete the one we're not
      toDel[i] <- e1
    }

  }

  # Now delete all the unneeded edges
  g <- g - E(g)[toDel]

  return(g)
}

set.seed(123)

g <- graph_from_literal(A-+B, B++C, A++C)
E(g)$weight <- round(runif(ecount(g),1,20))
weight0 <- E(g)$weight

gNet <- nettedGraph(g)

【讨论】:

  • igraph 的内部图数据结构的构造方式是删除一条边与删除多条边的时间复杂度大致相同。因此,我只需在for 循环中收集要删除的边的 ID,然后在最后一批中删除它们。
  • 谢谢,这是一个很好的提示。如果我考虑一下,我什至可以一起摆脱 for 循环。
猜你喜欢
  • 1970-01-01
  • 2018-07-03
  • 2014-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2016-10-19
  • 2013-12-04
相关资源
最近更新 更多