【问题标题】:How to assign a vector of values to a vertex label in igraph in R?如何将值向量分配给R中igraph中的顶点标签?
【发布时间】:2022-01-16 22:05:30
【问题描述】:

假设,我在igraph 中有一个包含 3 个节点和 3 条边的图,如下所示:

library(igraph)
G <- graph(c(1,2,1,3,2,3),directed = FALSE)
V(G)$myLabel <- 1:3

它工作得很好。但我想为每个节点分配一个不同长度的标签。例如:

G <- graph(c(1,2,1,3,2,3),directed = FALSE)
V(G)[1]$myLabel <- c(10,20)
V(G)[2]$myLabel <- c(-1,-2,-3)
V(G)[3]$myLabel <- c(100,200,300,400)

在我对图表的分析过程中,每个节点的标签长度​​可能会发生变化。我该怎么做?

【问题讨论】:

    标签: r igraph graph-algorithm


    【解决方案1】:

    您必须将长度为 1 的对象分配给节点。 否则,只会采用第一个元素。 但是,您可以使用list 封装向量以满足该要求:

    library(igraph)
    #> 
    #> Attaching package: 'igraph'
    #> The following objects are masked from 'package:stats':
    #> 
    #>     decompose, spectrum
    #> The following object is masked from 'package:base':
    #> 
    #>     union
    
    G <- graph(c(1,2,1,3,2,3),directed = FALSE)
    
    V(G)[1]$myLabel <- list(c(10,20))
    V(G)[2]$myLabel <- list(c(-1,-2,-3))
    V(G)[3]$myLabel <- list(c(100,200,300,400))
    
    V(G)[1]$myLabel
    #> [[1]]
    #> [1] 10 20
    V(G)[2]$myLabel
    #> [[1]]
    #> [1] -1 -2 -3
    V(G)[3]$myLabel
    #> [[1]]
    #> [1] 100 200 300 400
    
    # adding a new label to one node
    V(G)[3]$myLabel <- list(c(V(G)[3]$myLabel[[1]], 500))
    V(G)[3]$myLabel
    #> [[1]]
    #> [1] 100 200 300 400 500
    

    reprex package (v2.0.1) 于 2021 年 12 月 13 日创建

    【讨论】:

    • 谢谢!这可行,但是在像上面这样初始化之后,如果我现在更改 V(G)[3]$myLabel
    • 你需要的列表:V(G)[3]$myLabel &lt;- list(1:10)
    猜你喜欢
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多