首页 > 解决方案 > 在 r 中使用 igraph 向图形添加属性

问题描述

我有一个 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

标签: rigraph

解决方案


以下对我有用:

for (nm in names(attribs)) g <- set_vertex_attr(g, nm, value = attribs[[nm]])

V(g)$birthday
## [1] 6971  841 6971  841

推荐阅读