r - 如何使用预定义布局保存 igraph 对象的边列表?

标签 r dataframe igraph

我已阅读 R igraph - save layout? ,但在我的例子中,需要将开始和结束边缘的位置与边缘列表一起保存到一个文件中。

我在平面上有一个 tree igraph 对象和预定义的 mylayout 布局。

tree <- make_tree(5, 2, mode = "undirected")
mylayout <- matrix(c(1, 2, 0, 3, 2, 
                     1, 2, 0, 2, 3), ncol=2)

我添加了一个新属性name

tree <- make_tree(5, 2, mode = "undirected") %>% 
            set_vertex_attr("name", value = seq(1:vcount(tree)))

我通过 get.edgelist() 函数获取图的边列表,并且我将使用 name 属性:

   df1 <- data.frame(V1 = get.edgelist(tree)[,1], 
                  V2 = get.edgelist(tree)[,2], 
#           V1_x = mylayout[as.integer(names(V(tree))), 1],
#           V1_y = mylayout[as.integer(names(V(tree))), 2],
#           V2_x = mylayout[, 1],
#           V2_y = mylayout[, 2],
            stringsAsFactors = FALSE)

问题。如何将节点位置与边的开始和结束位置匹配?

最佳答案

我不知道是否有现有的方法可以做到这一点,但是编写一个辅助函数来做到这一点并不需要太多工作

join_layout <- function(g, layout) {
  edges <- as_edgelist(g)
  idx1 <- match(edges[,1], V(g)$name)
  idx2 <- match(edges[,2], V(g)$name)
  result <- cbind(data.frame(edges),
        layout[idx1, ],
        layout[idx2, ]
  )
  names(result) <- c("V1", "V2", "V1_x", "V1_y", "V2_x","V2_y")
  result
}

基本上,我们使用 match() 将顶点名称与布局矩阵中的行进行匹配。您可以通过传入 igraph 对象和布局来调用它

join_layout(tree, mylayout)
#   V1 V2 V1_x V1_y V2_x V2_y
# 1  1  2    1    1    2    2
# 2  1  3    1    1    0    0
# 3  2  4    2    2    3    2
# 4  2  5    2    2    2    3

关于r - 如何使用预定义布局保存 igraph 对象的边列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68798272/

相关文章:

r - 在 Shiny 中生成功能 sendSweetAlert 按钮

r - geom_raster 具有基于特定离散值的颜色

r - 使用 R 的 igraph 中的迭代器 V 和 E 如何工作?

r - 用 igraph 绘制社区

r - uniqueN 在 j 中的条件下返回错误结果

R:将数据框中的所有列相乘

r - 如何从使用管道分隔 R 中向量元素的字符串中解析出文本?

python - 如何在增量列值不存在的情况下复制行并增量列?

r - 如何将多列转换为观察值

R visNetwork : Multiple graph layout?