【问题标题】:Add attributes to graphs using igraph in r在 r 中使用 igraph 向图形添加属性
【发布时间】:2018-05-24 14:01:41
【问题描述】:

我有一个 csv 形式的特征数据集,可以在下面的链接中找到

https://github.com/pranavn91/PhD/blob/master/Expt/27022%20feat.csv

name    birthday    education   classes.from.id
27136   6971           NA              NA
27137   841            NA              NA
27138   841            NA              NA
27139   841            NA              NA

我有一个 csv 形式的图形邻接矩阵,可以在下面的链接中找到

https://github.com/pranavn91/PhD/blob/master/Expt/27022.csv

       27139    27138   27136   27137
27139   0         1       1      1
27138   1         0       0      0
27136   1         0       0      1
27137   1         0       1      0

我想将邻接矩阵转换为图形并设置顶点属性。 但是当我检查图的第一个顶点的生日时,我得到 841,即第二个节点的值。同样在边缘列表中,第一个节点的边缘也丢失了

library(igraph)
path <- "https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/27022.csv"
dat <- read.csv(path, row.names=1, check.names=FALSE, header=T)
m = as.matrix(dat)
g = graph.adjacency(m,mode="undirected",weighted=NULL)


path2 <- "https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/27022%20feat.csv"

prop <- read.csv(path2,row.names=1, check.names=FALSE, header=T)
head(prop)


for (i in V(g)) {
    for (j in names(prop)) {
        g <- set.vertex.attribute(g, 
                                           j, 
                                           index = i, 
                                           prop[i + 1, j])
    }
}


igraph::degree(g,v=V(g))
###degrees of nodes in g are 27136 - 3,  27137 - 1, 27138 - 2, 27139 - 2
###actual as per adjacency matrix should be 27136 - 2,  27137 - 2, 27138 - 1, 27139 - 3

【问题讨论】:

    标签: r igraph


    【解决方案1】:

    以下对我有用:

    for (nm in names(attribs)) g <- set_vertex_attr(g, nm, value = attribs[[nm]])
    
    V(g)$birthday
    ## [1] 6971  841 6971  841
    

    【讨论】:

    • 你检查了顶点 27022 的度数吗?根据邻接矩阵,它有 215 条边,但根据图对象,它只有 31 条边。
    • 我使用了您的示例数据,而不是巨大的 CSV 文件。可以发minimal reproducible example吗?
    • 我猜你可能需要在你的第一个read.csv 电话中使用header=TRUE
    • csv 不大。但我仍然用 MCVE 编辑了问题
    猜你喜欢
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多