igraph (version 0.7.0)

graph.structure: Method for structural manipulation of graphs

Description

These are the methods for simple manipulation of graphs: adding and deleting edges and vertices.

Usage

## S3 method for class 'igraph':
[(x, i, j, \dots, from, to,
                   sparse=getIgraphOpt("sparsematrices"),
                   edges=FALSE, drop=TRUE,
                   attr=if (is.weighted(x)) "weight" else NULL)
## S3 method for class 'igraph':
[[(x, i, j, \dots, directed=TRUE, edges=FALSE, exact=TRUE)
## S3 method for class 'igraph':
[(x, i, j, \dots, from, to,
                   attr=if (is.weighted(x)) "weight" else NULL) <- value 

## S3 method for class 'igraph': +(e1, e2) ## S3 method for class 'igraph': -(e1, e2) vertex(...) vertices(...) edge(...) edges(...) path(...)

add.edges(graph, edges, ..., attr=list()) add.vertices(graph, nv, ..., attr=list()) delete.edges(graph, edges) delete.vertices(graph, v)

Arguments

x,graph,e1
The graph to work on.
i,j
Vertex ids or names or logical vectors. See details below.
...
These are currently ignored for the indexing operators. For vertex, vertices, edge, edges and path see details below. For add.edges and add.vertices the
from
A numeric or character vector giving vertex ids or names. Together with the to argument, it can be used to query/set a sequence of edges. See details below.

This argument cannot be present together with any of the i

to
A numeric or character vector giving vertex ids or names. Together with the from argument, it can be used to query/set a sequence of edges. See details below.

This argument cannot be present together with any of the i

sparse
Logical scalar, whether to use sparse matrix.
directed
Logical scalar, whether to consider edge directions in directed graphs. It is ignored for undirected graphs.
edges
Logical scalar, whether to return edge ids.
drop,exact
These arguments are ignored.
value
A logical or numeric scalar or NULL. If FALSE, NULL or zero, then the specified edges will be deleted. If TRUE or a non-zero numeric value, then the specified edges will be added. (Only if
e2
See details below.
attr
For the indexing operators: if not NULL, then it should be the name of an edge attribute. This attribute is queried, or updated to the given value. For add.edges and add.vertices: additional edge/verte
nv
Numeric constant, the number of vertices to add.
v
Vector sequence, the vertices to remove.

Value

  • For the indexing operators see the description above. The other functions return a new graph.

The indexing operators

The one-bracket ([) and two-brackets ([[) indexing operators allow relatively straightforward query and update operations on graphs. The one bracket operator works on the (imaginary) adjacency matrix of the graph. Here is what you can do with it:

  1. Check whether there is an edge between two vertices ($v$and$w$) in the graph:graph[v, w]A numeric scalar is returned, one if the edge exists, zero otherwise.
  2. Extract the (sparse) adjacency matrix of the graph, or part of it:graph[] graph[1:3,5:6] graph[c(1,3,5),]The first variants returns the full adjacency matrix, the other two return part of it.
  3. Thefromandtoarguments can be used to check the existence of many edges. In this case, bothfromandtomust be present and they must have the same length. They must contain vertex ids or names. A numeric vector is returned, of the same length asfromandto, it contains ones for existing edges edges and zeros for non-existing ones. Example:graph[from=1:3, to=c(2,3,5)].
  4. For weighted graphs, the[operator returns the edge weights. For non-esistent edges zero weights are returned. Other edge attributes can be queried as well, by giving theattrargument.
  5. Querying edge ids instead of the existance of edges or edge attributes. E.g.graph[1, 2, edges=TRUE]returns the id of the edge between vertices 1 and 2, or zero if there is no such edge.
  6. Adding one or more edges to a graph. For this the element(s) of the imaginary adjacency matrix must be set to a non-zero numeric value (orTRUE):graph[1, 2] <- 1 graph[1:3,1] <- 1 graph[from=1:3, to=c(2,3,5)] <- TRUEThis does not affect edges that are already present in the graph, i.e. no multiple edges are created.
  7. Adding weighted edges to a graph. Theattrargument contains the name of the edge attribute to set, so it does not have to beweight:graph[1, 2, attr="weight"]<- 5 graph[from=1:3, to=c(2,3,5)] <- c(1,-1,4)If an edge is already present in the network, then only its weigths or other attribute are updated. If the graph is already weighted, then theattr="weight"setting is implicit, and one does not need to give it explicitly.
  8. Deleting edges. The replacement syntax allow the deletion of edges, by specifyingFALSEorNULLas the replacement value:graph[v, w] <- FALSEremoves the edge from vertex$v$to vertex$w$. As this can be used to delete edges between two sets of vertices, either pairwise:graph[from=v, to=w] <- FALSEor not:graph[v, w] <- FALSEif$v$and$w$are vectors of edge ids or names.

The double bracket operator indexes the (imaginary) adjacency list of the graph. This can used for the following operations:

  1. Querying the adjacent vertices for one or more vertices:graph[[1:3,]] graph[[,1:3]]The first form gives the successors, the second the predessors or the 1:3 vertices. (For undirected graphs they are equivalent.)
  2. Querying the incident edges for one or more vertices, if theedgesargument is set toTRUE:graph[[1:3, , edges=TRUE]] graph[[, 1:3, edges=TRUE]]
  3. Querying the edge ids between two sets or vertices, if both indices are used. E.g.graph[[v, w, edges=TRUE]]gives the edge ids of all the edges that exist from vertices$v$to vertices$w$.

Both the [ and [[ operators allow logical indices and negative indices as well, with the usual R semantics. E.g. graph[degree(graph)==0, 1] <- 1 adds an edge from every isolate vertex to vertex one, and G <- graph.empty(10) G[-1,1] <- TRUE creates a star graph.

Of course, the indexing operators support vertex names, so instead of a numeric vertex id a vertex can also be given to [ and [[.

The plus operator for adding vertices and edges

The plus operator can be used to add vertices or edges to graph. The actual operation that is performed depends on the type of the right hand side argument.
  • If is is another igraph graph object and they are both named graphs, then the union of the two graphs are calculated, seegraph.union.
  • If it is another igraph graph object, but either of the two are not named, then the disjoint union of the two graphs is calculated, seegraph.disjoint.union.
  • If it is a numeric scalar, then the specified number of vertices are added to the graph.
  • If it is a character scalar or vector, then it is interpreted as the names of the vertices to add to the graph.
  • If it is an object created with thevertexorverticesfunction, then new vertices are added to the graph. This form is appropriate when one wants to add some vertex attributes as well. The operands of theverticesfunction specifies the number of vertices to add and their attributes as well.

    The unnamed arguments ofverticesare concatenated and used as thenamevertex attribute (i.e. vertex names), the named arguments will be added as additional vertex attributes. Examples:g <- g + vertex(shape="circle", color="red") g <- g + vertex("foo", color="blue") g <- g + vertex("bar", "foobar") g <- g + vertices("bar2", "foobar2", color=1:2, shape="rectangle")See more examples below.vertexis just an alias tovertices, and it is provided for readability. The user should use it if a single vertex is added to the graph.

  • If it is an object created with theedgeoredgesfunction, then new edges will be added to the graph. The new edges and possibly their attributes can be specified as the arguments of theedgesfunction.

    The unnamed arguments ofedgesare concatenated and used as vertex ids of the end points of the new edges. The named arguments will be added as edge attributes.

    Examples:g <- graph.empty() + vertices(letters[1:10]) + vertices("foo", "bar", "bar2", "foobar2") g <- g + edge("a", "b") g <- g + edges("foo", "bar", "bar2", "foobar2") g <- g + edges(c("bar", "foo", "foobar2", "bar2"), color="red", weight=1:2)See more examples below.edgeis just an alias toedgesand it is provided for readability. The user should use it if a single edge is added to the graph.

  • If it is an object created with thepathfunction, then new edges that form a path are added. The edges and possibly their attributes are specified as the arguments to thepathfunction. The non-named arguments are concatenated and interpreted as the vertex ids along the path. The remaining arguments are added as edge attributes.

    Examples:g <- graph.empty() + vertices(letters[1:10]) g <- g + path("a", "b", "c", "d") g <- g + path("e", "f", "g", weight=1:2, color="red") g <- g + path(c("f", "c", "j", "d"), width=1:3, color="green")

It is important to note that, although the plus operator is commutative, i.e. is possible to write graph <- "foo" + graph.empty() it is not associative, e.g. graph <- "foo" + "bar" + graph.empty() results a syntax error, unless parentheses are used: graph <- "foo" + ( "bar" + graph.empty() ) For clarity, we suggest to always put the graph object on the left hand side of the operator: graph <- graph.empty() + "foo" + "bar"

The minus operator for deleting vertices and edges

The minus operator (-) can be used to remove vertices or edges from the graph. The operation performed is selected based on the type of the right hand side argument:
  • If it is an igraph graph object, then the difference of the two graphs is calculated, seegraph.difference.
  • If it is a numeric or character vector, then it is interpreted as a vector of vertex ids and the specified vertices will be deleted from the graph. Example:g <- graph.ring(10) V(g)$name <- letters[1:10] g <- g - c("a", "b")
  • Ife2is a vertex sequence (e.g. created by theVfunction), then these vertices will be deleted from the graph.
  • If it is an edge sequence (e.g. created by theEfunction), then these edges will be deleted from the graph.
  • If it is an object created with thevertex(or thevertices) function, then all arguments ofverticesare concatenated and the result is interpreted as a vector of vertex ids. These vertices will be removed from the graph.
  • If it is an object created with theedge(or theedges) function, then all arguments ofedgesare concatenated and then interpreted as edges to be removed from the graph. Example:g <- graph.ring(10) V(g)$name <- letters[1:10] E(g)$name <- LETTERS[1:10] g <- g - edge("e|f") g <- g - edge("H")
  • If it is an object created with thepathfunction, then allpatharguments are concatenated and then interpreted as a path along which edges will be removed from the graph. Example:g <- graph.ring(10) V(g)$name <- letters[1:10] g <- g - path("a", "b", "c", "d")

More functions to manipulate graph structure

add.edges adds the specified edges to the graph. The ids of the vertices are preserved. The additionally supplied named arguments will be added as edge attributes for the new edges. If an attribute was not present in the original graph, its value for the original edges will be NA.

add.vertices adds the specified number of isolate vertices to the graph. The ids of the old vertices are preserved. The additionally supplied named arguments will be added as vertex attributes for the new vertices. If an attribute was not present in the original graph, its value is set to NA for the original vertices.

delete.edges removes the specified edges from the graph. If a specified edge is not present, the function gives an error message, and the original graph remains unchanged. The ids of the vertices are preserved.

delete.vertices removes the specified vertices from the graph together with their adjacent edges. The ids of the vertices are not preserved.

Details

There are, by and large, three ways to manipulate the structure of a graph in igraph. The first way is using the [ and [[ indexing operators on the graph object, very much like the graph was an adjacency matrix ([) or an adjacency list ([). The single bracket indexes the (possibly weighted) adjacency matrix of the graph. The double bracket operator is similar, but queries the adjacencly list of the graph. The details on how to use the indexing operators are discussed below.

The addition (+) and division (-) operators can also be used to add and remove vertices and edges. This form is sometimes more readable, and is usually the best if the user also wants to add attributes, together with the new vertices/edges. Please see the details below.

In addition, the four functions, add.vertices, add.edges, delete.vertices and delete.edges can also be used to manipulate the structure.

Examples

Run this code
# 10 vertices named a,b,c,... and no edges
g <- graph.empty() + vertices(letters[1:10])

# Add edges to make it a ring
g <- g + path(letters[1:10], letters[1], color="grey")

# Add some extra random edges
g <- g + edges(sample(V(g), 10, replace=TRUE), color="red")
g$layout <- layout.circle
if (interactive()) {
  plot(g)
}

# The old-style operations
g <- graph.ring(10)
add.edges(g, c(2,6,3,7) )
delete.edges(g, E(g, P=c(1,10, 2,3)) )
delete.vertices(g, c(2,7,8) )

Run the code above in your browser using DataCamp Workspace