I’ve looked through the source for V and E and I’m not really sure how they work.
Here’s the code for V:
> V
function (graph)
{
if (!is.igraph(graph)) {
stop("Not a graph object")
}
vc <- vcount(graph)
if (vc == 0) {
res <- numeric()
}
else {
res <- 0:(vc - 1)
}
class(res) <- "igraph.vs"
ne <- new.env()
assign("graph", graph, envir = ne)
attr(res, "env") <- ne
res
}
I’m not really sure what purpose the calls to assign and attr serve here.
Does assigning graph create a new copy of graph? How efficient/inefficient is this? That is, how many copies of graph does this generate say in code like:
V(g)$someattr <- somevector
Thanks for the help.
When generating a vertex sequence with
V, the calls toassignandattrstore a copy of the graph that was used to create the sequence along with the vertex sequence object, itself. This way when you do something likeV(g)$color = 'blue', the vertex sequence can be conveniently evaluated in the context of this copy ofg. This is clear if you inspect one of the methods available for theigraph.vsclass.Here it is clear that the
$indexing operation will get evaluated in the context of the graph environment that was used to create the vertex sequence.You bring up a good point though that this does create multiple copies of the graph (which presumably get garbage collected, but it’s still good to be aware of). This is easily demonstrated if you modify attributes of a graph
g, after you have already created a vertex sequencevs = V(g). The attribute is updated ing, but not in the copy ofgthat is stored in the environment attached tovs.