【问题标题】:How to set an edge attribute for a network using statnet in R?如何在 R 中使用 statnet 为网络设置边缘属性?
【发布时间】:2019-03-31 11:56:07
【问题描述】:

我正在准备一些网络数据,以便使用 statnet 库在 R 中运行 ERGM。我想为运行 ERGM 时将使用的边缘分配一个属性。该矩阵包括网络中每个平局的 0 到 1 之间的数字。当我使用 set.edge.attribute 时出现错误,提示“set.edge.attribute 中给出的值不合适”。

我首先认为包含我要添加的属性的矩阵中的值可能存在问题。为了检查这一点,我创建了一个包含随机数的矩阵并再次运行 set.edge.attribute 代码,但仍然出现错误。

我将网络和边缘属性导入为 CSV 文件,将网络文件转换为网络对象,并将边缘属性转换为矩阵。边属性与网络中的边数相同。

library(statnet)
NetworkGraph = network(NetworkData,type="adjacency", directed=FALSE)
EdgeInfo = as.matrix(EdgeInfo) 
NetworkGraph<-set.edge.attribute(NetworkGraph,"edge_attribute", EdgeInfo)

为了生成一个属性矩阵来测试它,我使用 runif 创建了一个新矩阵,但仍然遇到同样的错误):

Test = matrix(runif(23*23), nrow=23, ncol=23)
NetworkGraph<-set.edge.attribute(NetworkGraph,"edge_attribute", Test)

什么能让这个工作?

【问题讨论】:

    标签: r statnet


    【解决方案1】:

    一种方法是直接从值矩阵创建网络:

    > library(network)
    
    # create a small test matrix
    > gvalues<-matrix(runif(5*5),nrow=5,ncol=5)
    > gvalues
              [,1]       [,2]      [,3]       [,4]       [,5]
    [1,] 0.6456140 0.88881086 0.2855281 0.79027269 0.01526509
    [2,] 0.4825466 0.64184675 0.4456986 0.44277690 0.27018424
    [3,] 0.5276330 0.04742485 0.7675878 0.05453299 0.36940432
    [4,] 0.3188620 0.52574674 0.1642077 0.07034616 0.60229633
    [5,] 0.3741370 0.22432400 0.8093938 0.24704229 0.29042967
    
    # convert to network object, telling it to *not* ignore edge values
    # and also name the edge values 'testValue'
    > g <- as.network(gvalues,ignore.eval = FALSE, loops=TRUE, names.eval='testValue')
    
    # check that the edge value was added. since it was a full matrix, it should be a 'complete' network with 25 edges connecting all nodes
    > g
     Network attributes:
      vertices = 5 
      directed = TRUE 
      hyper = FALSE 
      loops = TRUE 
      multiple = FALSE 
      bipartite = FALSE 
      total edges= 25 
        missing edges= 0 
        non-missing edges= 25 
    
     Vertex attribute names: 
        vertex.names 
    
     Edge attribute names: 
        testValue 
    
    # convert network back to a matrix to check if it worked
    > as.matrix(g,attrname = 'testValue')
              1          2         3          4          5
    1 0.6456140 0.88881086 0.2855281 0.79027269 0.01526509
    2 0.4825466 0.64184675 0.4456986 0.44277690 0.27018424
    3 0.5276330 0.04742485 0.7675878 0.05453299 0.36940432
    4 0.3188620 0.52574674 0.1642077 0.07034616 0.60229633
    5 0.3741370 0.22432400 0.8093938 0.24704229 0.29042967
    

    我包含了loops=TRUE 参数,因为输入矩阵在对角线上有值,否则不需要这个。如果要从matrix 向现有网络添加边缘属性,则需要使用set.edge.value() 而不是set.edge.attribute()。这似乎没有记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多