【问题标题】:R/Network Analysis - How to create edges by node's attributesR/网络分析 - 如何通过节点的属性创建边
【发布时间】:2017-03-25 17:56:13
【问题描述】:

尊敬的 Stackoverflow 社区,

我目前正在使用 R 编译一个附属网络,其中节点是公司/伞式组织,关系被定义为“成员”。目前,我的列表仍然很小,我可以根据节点的位置创建如下边(我使用 igraph):

g <- igraph::add_edges(g, c(1,51,
                          1,52,
                          1,53,
                          1,54))

但是,我正在添加新节点,最终网络将包括至少 500 个组织。这意味着每次添加新节点时节点的位置都会发生变化。由于每次添加新节点时都无法重做边缘,有没有办法可以添加知道节点名称的边缘?

节点的名称被视为一个属性,我尝试使用与上面相同的命令,包括名称 - 而不是位置 - 但它不起作用:

g <- igraph::add_edges(g, c(V(g)$name=="Company1", V(g)$name == "Umbrella2"))

关于如何通过指定名称而不是位置来创建边缘的任何建议?

【问题讨论】:

    标签: r igraph vertices edges network-analysis


    【解决方案1】:

    我相信你正在寻找as.numeric(V(g)["Company1"])

    不过,我强烈建议反对 R 脚本中构建您的网络结构。即使对于一个小型网络,我也会将我的数据输入到一个 excel 文件中,创建一个 R 脚本,将数据作为边缘列表读取并从中创建一个 igraph。这样一来,您可以随时添加您的公司和组织,从而更好地监督哪些数据实际进入您的网络,我想这就是您首先要寻找的。不过,在这里这样做会超出这个问题的范围。

    至于按名称添加节点,我为您编写了这个示例,希望具有教学意义。

    library(igraph)
    
    # Make an empty Bipartite graph
    g <- make_bipartite_graph(0, NULL, directed=TRUE)
    g <- delete_vertices(g, 1)
    
    
    # Create vertices of two different types: companies and umbrellas
    g  <- add_vertices(g, 5, color = "red", type=TRUE, name=paste("Company", 1:5, sep="_"))
    g  <- add_vertices(g, 2, color = "blue", type=FALSE, name=paste("Umbrella", 1:2, sep="_"))
    
    # In a bipartate graph edges may only appear BETWEEN verticies of different types. Companies
    # can belong to umbrellas, but not to each other.
    
    # Look at the types:
    ifelse(V(g)$type, 'Company', 'Umbrella')  # true for companies, false for umbrellas
    
    # Lets add some edges one by one. This is what I believe you're asking for in the question:
    g <- add_edges(g, c(as.numeric(V(g)["Company_1"]), as.numeric(V(g)["Umbrella_1"])))
    g <- add_edges(g, c(as.numeric(V(g)["Company_1"]), as.numeric(V(g)["Umbrella_2"])))
    g <- add_edges(g, c(as.numeric(V(g)["Company_2"]), as.numeric(V(g)["Umbrella_1"])))
    g <- add_edges(g, c(as.numeric(V(g)["Company_3"]), as.numeric(V(g)["Umbrella_1"])))
    g <- add_edges(g, c(as.numeric(V(g)["Company_4"]), as.numeric(V(g)["Umbrella_2"])))
    g <- add_edges(g, c(as.numeric(V(g)["Company_5"]), as.numeric(V(g)["Umbrella_2"])))
    
    # Note that "Company_1" belongs to two umbrella organisations, as I assume your companies can:
    plot(g)
    

    【讨论】:

    • 谢谢,这很有用。该命令适用于我当前的数据,但我同意我应该先编译一个 Excel 电子表格。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多