gpt4 book ai didi

r - 如何在 igraph 中添加数据框作为具有匹配 id 的顶点属性?

转载 作者:行者123 更新时间:2023-12-04 09:21:14 25 4
gpt4 key购买 nike

在 R 中,我有一个加权无向图作为 igraph 对象:

IGRAPH e7a8fac UNW- 306 2829 -- 
+ attr: name (v/c), label (v/c), nom (v/c), sigle (v/c), statut (v/c), champ (v/c), cp (v/c), info (v/c), weight (e/n)
+ edges from e7a8fac (vertex names):
[1] 3 --9 7 --13 7 --15 13--15 11--16 15--17 6 --18 13--20 15--20 20--21 6 --25 18--25 6 --28 10--28 15--28 17--28 18--28 20--28 25--28
[20] 23--30 15--31 17--31 28--31 6 --33 17--33 18--33 22--33 25--33 28--33 7 --34 13--34 15--34 17--34 16--35 34--36 15--37 18--37 20--37
[39] 25--37 28--37 13--43 17--43 18--43 25--43 28--43 33--43 34--43 11--44 13--44 20--44 23--44 30--44 31--44 34--44 40--45 13--47 43--47
[58] 44--47 13--48 15--48 16--48 17--48 20--48 28--48 31--48 34--48 37--48 44--48 45--48 21--54 13--58 34--58 44--58 48--58 10--61 15--61
+ ... omitted several edges

我使用另一个包 (tnet) 来计算几个指标。最后,我有一个包含 4 列的数据框:
     id degree strength degree_alpha
[1,] 1 0 0.00000 0.000000
[2,] 2 2 3.00000 2.449490
[3,] 3 1 2.00000 1.414214
[4,] 4 1 2.00000 1.414214
[5,] 5 0 0.00000 0.000000
[6,] 6 25 19.10897 21.856906

我想添加三列( degreestrengthdegree_alpha )作为具有匹配 ID 的顶点属性(数据框中的列 id,igraph 中的属性 name)。

易图 set_vertex_attr似乎是要使用的工具,但我不知道如何让它通过数据框并且只向现有节点添加属性。

最佳答案

对我来说,我认为最简单的方法是:

  • 使用 igraph::as_data_frame 将图转换为节点和边列表
  • 如果您输入参数 what = 'both',您实际上会得到一个数据框列表。
  • 将数据合并到节点列表
  • 使用更新的节点列表和边列表使用 graph_from_data_frame 重新创建图形

  • .
    library(dplyr)

    g <- make_graph('zachary') %>%
    set_edge_attr(., 'weight', value = runif(ecount(.), 1, 10)) %>%
    set_vertex_attr(., 'name', value = V(.) %>% as.numeric)

    fake_data <- tibble(
    id = V(g) %>% as.numeric(),
    degree = degree(g),
    strength = strength(g)
    )

    df <- igraph::as_data_frame(g, 'both')

    df$vertices <- df$vertices %>%
    left_join(fake_data, c('name'='id'))

    updated_g <- graph_from_data_frame(df$edges,
    directed = F,
    vertices = df$vertices)

    如果您不想从数据格式来回转换,那么可以,您可以使用 set_vertex_attr .
  • 遍历顶点向量 V(g)
  • 您无法迭代顶点向量,您需要迭代所有顶点都具有的顶点属性。
  • 将数据框过滤到与每个向量匹配的行
  • 返回感兴趣的值

  • .
    updated_g2 <- g %>%
    set_vertex_attr(.,
    name = 'degree',
    index = V(g),
    value = sapply(V(g)$name, function(x){
    fake_data %>%
    filter(id == x) %>%
    .$degree
    })) %>%
    set_vertex_attr(.,
    name = 'strength',
    index = V(g),
    value = sapply(V(g)$name, function(x){
    fake_data %>%
    filter(id == x) %>%
    .$strength
    }))

    关于r - 如何在 igraph 中添加数据框作为具有匹配 id 的顶点属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49728990/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com