Search code examples
rdirected-acyclic-graphspcalg

How to get the adjacency matrix from the dag?


I know how to generate a DAG.

library(pcalg)
dag <- randDAG(10, 1, "er") 

But now I need to get the adjacency matrix of the above dag. I guess there exists such a function but I don't know what it is.

The chatgpt give me the false result:

# Get the adjacency matrix from the DAG
adjacency_matrix <- amat(dag)

# Print or inspect the adjacency matrix
print(adjacency_matrix)

But unfortunately, Error in amat(dag) : could not find function "amat"


Solution

  • You can use showAmat

    library(pcalg)
    
    dag <- randDAG(10, 1, "er") 
    amat <- showAmat(dag)
    amat
    #>    1         2 3 4         5 6         7         8 9 10
    #> 1  0 0.0000000 0 0 0.4144231 0 0.0000000 0.0000000 0  0
    #> 2  0 0.0000000 0 0 0.0000000 0 0.0000000 2.0000000 0  0
    #> 3  0 0.0000000 0 0 0.0000000 0 0.7542406 0.7771955 0  0
    #> 4  0 0.0000000 0 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 5  2 0.0000000 0 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 6  0 0.0000000 0 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 7  0 0.0000000 2 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 8  0 0.3098213 2 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 9  0 0.0000000 0 0 0.0000000 0 0.0000000 0.0000000 0  0
    #> 10 0 0.0000000 0 0 0.0000000 0 0.0000000 0.0000000 0  0