Randomly generated adjacency matrix in R I'm wanting to generate random connected directed acyclic graphs, and am wondering if there is a way of populating an adjacency matrix in R which would represent the aforementioned.
Something similar to this would be nice (that is done with Mathematica): https://mathematica.stackexchange.com/q/608
Thanks.
 A: The question asks for a random lower triangular binary matrix which represents the edges.  Here is one way, with the number of vertices (as v) and number of edges stipulated and edges chosen independently and uniformly among the available ones:
DAG.random <- function(v, nedges=1) {
    edges.max <- v*(v-1)/2
    # Assert length(v)==1 && 1 <= v
    # Assert 0 <= nedges <= edges.max
    index.edges <- lapply(list(1:(v-1)), function(k) rep(k*(k+1)/2, v-k)) 
    index.edges <- index.edges[[1]] + 1:edges.max
    graph.adjacency <- matrix(0, ncol=v, nrow=v)
    graph.adjacency[sample(index.edges, nedges)] <- 1
    graph.adjacency
}

This solution uses R's simultaneous use of matrix and array indexing.  index.edges computes a list of the array indexes corresponding to the lower triangular elements of graph.adjacency.  (This is done by finding the gaps in these indexes left by the diagonal and upper triangular entries and shifting the sequence c(1,2,3,...) by those gaps.)  Sampling the indexes (without replacement) does the trick.
Edit
One ad-hoc way to create connected DAGs is by adjoining a connected "skeleton" to the random DAG in a way that keeps it acyclic.  For instance, we can create a linear skeleton post hoc:
set.seed(17)
n <- 6; e <- 4
a <- DAG.random(n, e)
a[seq(from=2, by=n+1, length.out=n-1)] <- 1

Here's the adjacency matrix:
> a
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    0    0    0    0
[2,]    1    0    0    0    0    0
[3,]    0    1    0    0    0    0
[4,]    1    1    1    0    0    0
[5,]    0    0    0    1    0    0
[6,]    0    0    0    1    1    0

