Reputation: 213
I want to set vertex attributes in a large network (20k nodes). For simplicity here is a sample of the edgelist:
library(igraph)
el <- matrix( c(1, 2,1,3,1,4,2,3,2,5,3,6,3,7,3,8,3,9,12,13,13,14 ), nc = 2, byrow = TRUE)
el[,1] = as.character(el[,1])
el[,2] = as.character(el[,2])
g = graph.data.frame(el,directed=FALSE)
Also, I have a data frame that looks like this:
ID = c(1,2,3,4,5,6,7,8,9,NA,NA)
Attr1 = c(12,13,14,NA,14,13,16,NA,24,13,15)
Attr2 = c(NA, "bb", "cc","ff","dd",NA,"hh",NA,"kk","dd","cc")
Attributes = data.frame(ID, Attr1, Attr2)
rm(Attr1)
rm(Attr2)
rm(ID)
I want to use the data from the Attributes data frame as vertex attributes. As in the example, some of the data is missing (e.g. some vertices in the network are not represented in the Attributes data frame). The number of rows in the data frame matches the number of vertices. I want to add the attributes using the ID for matching (the IDs in the edgelist and the Attributes dataframe are mostly the same, however some IDs are only in either the edgelist or the dataframe).
Upvotes: 0
Views: 2507
Reputation: 199
there is a fast way to set attribute, you can consider.
V(g)$ID <- c(1,2,3,4,5,6,7,8,9,NA,NA)
V(g)$Attr1 <- c(12,13,14,NA,14,13,16,NA,24,13,15)
V(g)$Attr2 <- c(NA, "bb", "cc","ff","dd",NA,"hh",NA,"kk","dd","cc")
Upvotes: 1
Reputation: 37661
set_vertex_attr
will do this
Updating answer so that names and values are taken from the dataframe
for(cn in colnames(Attributes)) {
g = set_vertex_attr(g, cn, 1:nrow(Attributes), value=Attributes[,cn])
}
Upvotes: 2