How to get adjacency matrix from the graph in R?

I am using pcalg package in R.

library(pcalg)
## Load predefined data
data(gmG)
## Define the score (BIC)
score <- new("GaussL0penObsScore", gmG8$x)
## Estimate the essential graph
ges.fit <- ges(score)

plot(ges.fit$essgraph)   

I only know how to plot the graph. But I need the adjacency matrix from the ges.fit.

I think you want the adjacency matrix from gmG

library(graph)
#> Loading required package: BiocGenerics
#> 
#> Attaching package: 'BiocGenerics'
#> The following objects are masked from 'package:stats':
#> 
#>     IQR, mad, sd, var, xtabs
#> The following objects are masked from 'package:base':
#> 
#>     anyDuplicated, aperm, append, as.data.frame, basename, cbind,
#>     colnames, dirname, do.call, duplicated, eval, evalq, Filter, Find,
#>     get, grep, grepl, intersect, is.unsorted, lapply, Map, mapply,
#>     match, mget, order, paste, pmax, pmax.int, pmin, pmin.int,
#>     Position, rank, rbind, Reduce, rownames, sapply, setdiff, sort,
#>     table, tapply, union, unique, unsplit, which.max, which.min
library(igraph)
#> 
#> Attaching package: 'igraph'
#> The following objects are masked from 'package:graph':
#> 
#>     degree, edges, intersection, union
#> The following objects are masked from 'package:BiocGenerics':
#> 
#>     normalize, path, union
#> The following objects are masked from 'package:stats':
#> 
#>     decompose, spectrum
#> The following object is masked from 'package:base':
#> 
#>     union
library(pcalg)
data(gmG)
g <- gmG$g
ig <- igraph.from.graphNEL(g)
sparse_matrix <- as_adjacency_matrix(ig)
adjacency_matrix <- as.matrix(sparse_matrix)
adjacency_matrix
#>        Author Bar Ctrl Goal V5 V6 V7 V8
#> Author      0   1    0    0  0  1  0  1
#> Bar         0   0    1    0  1  0  0  0
#> Ctrl        0   0    0    0  0  0  0  0
#> Goal        0   0    0    0  0  0  0  0
#> V5          0   0    0    0  0  1  0  1
#> V6          0   0    0    0  0  0  1  0
#> V7          0   0    0    0  0  0  0  0
#> V8          0   0    0    0  0  0  0  0

Created on 2023-09-01 with reprex v2.0.2

Your codes work in your example. But I have to use the graph generated from ges.fit. Then I get the error using igraph.from.graphNEL function. It says "Error in igraph.from.graphNEL(ges.fit) : Not a graphNEL graph".

But I guess it's doable to call the graph from ges.fit. For example, ges.fit$repr gives us below:

$repr
Reference class object of class "GaussParDAG"
Field ".nodes":
[1] "Author" "Bar"    "Ctrl"   "Goal"   "V5"     "V6"     "V7"    
[8] "V8"    
Field ".in.edges":
[[1]]
integer(0)

[[2]]
[1] 1

[[3]]
[1] 2

[[4]]
integer(0)

[[5]]
[1] 2

[[6]]
[1] 1 5

[[7]]
[1] 6

[[8]]
[1] 1 5

I get it.

as(ges.fit$essgraph, "graphNEL")

can fix the gap. Thank you so much!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.