我正在从边缘列表创建一个igraph对象,然后向节点添加属性。
library(tidyverse)
require(dplyr)
library(readr)
library(igraph)
#edge list
edge_df <- read.table("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.edges", header = F, sep = " ", numerals="no.loss")
#attributes
full_ego_friends_feat_circles_df <- read.table("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.feat", header = F, numerals="no.loss")
#names of different attributes
feat_desc_file_df <- readLines("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.featnames")
column_names <- append("nodeid",feat_desc_file_df)
colnames(full_ego_friends_feat_circles_df)<-column_names
#create a graph from edge list
g <- graph_from_data_frame(edge_df, directed = TRUE)
#add attribute to nodes by searching and matching
V(g)$"0 gender:1"=full_ego_friends_feat_circles_df$"0 gender:1"[match(as.numeric(V(g)$name),as.numeric(levels(full_ego_friends_feat_circles_df$nodeid))[full_ego_friends_feat_circles_df$nodeid]
)]
数据框中的第一个属性(feat_desc_file_df)是“0 gender:1”,它被添加。但是在数据框架(feat_desc_file_df)中有1318个属性名称。对于每一个我必须搜索和匹配,因为我有“0性别:1”最好的方式
答案 0 :(得分:0)
希望我能理解你的问题。我认为一个简单的解决方案可能是遍历属性表的各个列。
然后根据与顶点ID的匹配对属性进行排序,并使用set_vertex_attr函数为每个节点设置属性。
# Load data
edgelist <- read.table("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.edges", header = F, sep = " ", numerals="no.loss")
graph <- graph_from_data_frame(edgelist)
attribute_table <- read.table("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.feat", header = F, numerals="no.loss")
attr_names <- readLines("https://raw.githubusercontent.com/pranavn91/PhD/master/Expt/100129275726588145876.featnames")
attr_names <- append("id", attr_names)
names(attribute_table)<-attr_names
# Loop through the attribute dataframe to add an attribute at the time, using the set_vertex_attribute function.
for (i in 2:length(attribute_table)){
# Select attributes
temp_attribute <- attribute_table[,c(1,i)]
# Match the attribute id with the id of the graph vertexes
sorted_attr<- temp_attribute[match(temp_attribute[,1], V(graph)$name),2]
# Set attributes
graph <- set_vertex_attr(graph, name = (names(attribute_table)[i]),
index = V(graph), value = sorted_attr)
}