igraph vertex attributes graph_from_data_frame best practices

Viewed 155

I am working with igraph in R with a huge network and I am a bit afraid of messing the df up. I followed Vertex/node attributes for igraph objects and read R-igraph tutorials and docs.

Yet, I am missing something suppose I have this data:

toy_data = data.table(source = c(1,1,1,3,5,5,1,1,1,3,5,5), 
                      source_name=c(Milan,Milan,Milan,Frankfurt,London,London,Milan,Milan,Milan,Frankfurt,London,London), 
                      from=c("A","A","A","C","E","E","A","A","A","C","E","E"),
                      target=c(2,3,1,4,6,5,5,1,1,1,3,NA), target_name=c(Paris,3,1,4,6,5,5,1,1,1,3,NA),
                      to=c("B","C","A","D","F","E","E","A","A","A","C",NA))
edges <- toy_data[,.(source,target)]
v <- data.frame(labels=as.character(unique(unlist(toy_data[,.(source,target)]))),
                names = as.character(unique(unlist(toy_data[,.(source_name,target_name)]))),
                category = as.character(unique(unlist(toy_data[,.(from,to)]))))
graph <- graph_from_data_frame(edges, vertices = v, directed = FALSE)
plot(graph,vertex.label=v$names,vertex.color=c("pink","skyblue")[1+(V(graph)$category=="A")]) 

All good as long as the "unique" vectors unlisted have the same length, but to me it doesn't seem a very good practice to individually load vertex attributes as separate columns since it is enough to have one duplicate (here from and to fields have "A" for Frankfurt instead of "C") that the vectors are not equal-sized any longer:

toy_data = data.table(source = c(1,1,1,3,5,5,1,1,1,3,5,5), 
           source_name= c("Milan","Milan","Milan","Frankfurt","London","London","Milan","Milan","Milan","Frankfurt","London","London"), 
           from=c("A","A","A","A","E","E","A","A","A","A","E","E"), 
           target=c(2,3,1,4,6,5,5,1,1,1,3,NA), 
           target_name=c("Paris","Frankfurt","Milan","Dublin","Madrid","London","London","Milan","Milan","Milan","Frankfurt",NA),
           to=c("B","A","A","D","F","E","E","A","A","A","A",NA))
toy_data
edges <- toy_data[,.(source,target)]
v <- data.frame(labels=as.character(unique(unlist(toy_data[,.(source,target)]))),
                names = as.character(unique(unlist(toy_data[,.(source_name,target_name)]))),
                category = as.character(unique(unlist(toy_data[,.(from,to)]))))
graph <- graph_from_data_frame(edges, vertices = v, directed = FALSE)
plot(graph,vertex.label=v$names,vertex.color=c("pink","skyblue")[1+(V(graph)$category=="A")]) 

So if I have a data.table structured already in this way how could I tell igraph to bind the node id to some features? (sort of zip() function in python?)

0 Answers
Related