【问题标题】:Create hierarchical network创建分层网络
【发布时间】:2016-04-25 09:48:38
【问题描述】:

在 R 中有一种方法可以创建这样的分层网络吗?

也就是说,在它生成一个由 5 个节点组成的集线器之前,其他 4 个集线器连接到这些集线器,依此类推,直到获得通用网络。

我想我可以使用make_tree igraph 功能,但我不知道如何迭代添加集线器。 这就是我所做的。

net <- make_tree(n = 5, children = 4, mode = "undirected")
plot(net)

谢谢

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    不确定这有多优雅。要让情节看起来像你的情节需要更多的工作,但我认为图表是正确的。

    library(igraph)
    
    #' This adds the gadd graph to the main graph, g, and wires all of its vertices
    #' to the central vertex of g
    attach_to_center <- function(g, gadd) {
      g <- g + gadd + edges(as.vector(rbind(1, gorder(g) + 1:gorder(gadd))))
    }
    
    nIter <- 2
    nChild <- 4
    
    # The initial graph
    g <- make_empty_graph(5, directed = FALSE) + edges(1,2,1,3,1,4,1,5,2,3,3,4,4,5,5,2)
    
    for (j in 1:nIter) {
      g0 <- g
      for (i in 1:nChild) {
        g <- attach_to_center(g, g0)
      }
    }
    
    plot(g, vertex.label = NA)
    

    这似乎足够快(尽管超过 3 或 4 次迭代后绘图就失控了)。

    【讨论】:

      【解决方案2】:

      我有类似的要求。以下代码生成图,除了中心子图的旋转。

      n = 5
      periphery = c(2,3,4,5)
      
      #Make the seed graph.
      g <- make_empty_graph(n, directed = FALSE) + edges(1,2,1,3,1,4,1,5,2,3,2,4,2,5,3,4,3,5,4,5)
      g_main <- make_empty_graph(directed = FALSE)
      
      #Create the layout for the initial 5 nodes.
      xloc <- c(0,.5,.5,-.5,-.5)
      yloc <- c(0,-.5,.5,.5,-.5)
      #Shift for each iteration.
      xshift <- 3*xloc
      yshift <- 3*yloc
      
      xLocMain <- c()
      yLocMain <- c()
      allperifery <- c()
      
      for (l in 1:n) {
        g_main <- g_main + g
        xLocMain <- c(xLocMain, xloc + xshift[l])
        yLocMain <- c(yLocMain, yloc + yshift[l])
        if (l != 1) {
          #Calculate periphery nodes.
          allperifery <- c(allperifery, (l-1)*n + periphery)
        }
      }
      #Connect each periphery node to the central node.
      for (y in allperifery) {
        g_main <- g_main + edges(1, y)
      }
      
      ## Repeat the same procedure for the second level.
      xLocMM <- c()
      yLocMM <- c()
      
      xshiftNew <- 10*xloc
      yshiftNew <- 10*yloc
      
      g_mm <- make_empty_graph(directed = FALSE)
      allpp <- c()
      for (l in 1:n) {
        g_mm <- g_mm + g_main
        xLocMM <- c(xLocMM, xLocMain + xshiftNew[l])
        yLocMM <- c(yLocMM, yLocMain + yshiftNew[l])
        if (l != 1) {
          allpp <- c(allpp, (l-1)*(n*n) + allperifery)
        }
      }
      
      for (y in allpp) {
        g_mm <- g_mm + edges(1, y)
      }
      
      l <- matrix(c(rbind(xLocMM, yLocMM)), ncol=2, byrow=TRUE)
      plot(g_mm, vertex.size=2, vertex.label=NA, layout = l)
      

      生成的图表是:

      必须提及每个节点的位置并将其传递给plot函数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 2017-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多