有时,使用图的标准表示形式(如邻接矩阵)会很有用。
用法
as_adjacency_matrix(
graph,
type = c("both", "upper", "lower"),
attr = NULL,
edges = deprecated(),
names = TRUE,
sparse = igraph_opt("sparsematrices")
)
参数
- graph
要转换的图。
- type
指定如何为无向图创建邻接矩阵。对于有向图,此参数会被忽略。可能的值:
upper
:使用矩阵的右上三角部分,lower
:使用矩阵的左下三角部分。both
:使用整个矩阵,返回对称矩阵。- attr
可以是
NULL
或一个字符串,指定边的属性名称。如果为NULL
,则返回传统的邻接矩阵。如果不是NULL
,则邻接矩阵中会包含给定边属性的值。如果图有多条边,则会包含(对于多条边)任意选择的边的边属性。如果edges
为TRUE
,则此参数会被忽略。请注意,这仅适用于某些属性类型。如果
sparse
参数为TRUE
,则属性必须是逻辑值或数值。如果sparse
参数为FALSE
,则也允许使用字符。 造成这种差异的原因是Matrix
包尚不支持字符稀疏矩阵。- edges
- names
逻辑常量,指示是否为矩阵分配行和列名称。 仅当图中存在
name
顶点属性时,才会分配这些名称。- sparse
逻辑标量,指示是否创建稀疏矩阵。 必须安装“
Matrix
”包才能创建稀疏矩阵。
详细信息
as_adjacency_matrix()
返回图的邻接矩阵。如果 sparse
为 FALSE
,则返回常规矩阵;如果 sparse
为 TRUE
,则返回稀疏矩阵,如 “Matrix
” 包中所定义。
示例
g <- sample_gnp(10, 2 / 10)
as_adjacency_matrix(g)
#> 10 x 10 sparse Matrix of class "dgCMatrix"
#>
#> [1,] . 1 1 . . . . . . .
#> [2,] 1 . 1 . . . . 1 . .
#> [3,] 1 1 . . . . . . . .
#> [4,] . . . . . . . 1 1 .
#> [5,] . . . . . . . 1 1 .
#> [6,] . . . . . . . 1 . .
#> [7,] . . . . . . . 1 . .
#> [8,] . 1 . 1 1 1 1 . . 1
#> [9,] . . . 1 1 . . . . .
#> [10,] . . . . . . . 1 . .
V(g)$name <- letters[1:vcount(g)]
as_adjacency_matrix(g)
#> 10 x 10 sparse Matrix of class "dgCMatrix"
#> [[ suppressing 10 column names ‘a’, ‘b’, ‘c’ ... ]]
#>
#> a . 1 1 . . . . . . .
#> b 1 . 1 . . . . 1 . .
#> c 1 1 . . . . . . . .
#> d . . . . . . . 1 1 .
#> e . . . . . . . 1 1 .
#> f . . . . . . . 1 . .
#> g . . . . . . . 1 . .
#> h . 1 . 1 1 1 1 . . 1
#> i . . . 1 1 . . . . .
#> j . . . . . . . 1 . .
E(g)$weight <- runif(ecount(g))
as_adjacency_matrix(g, attr = "weight")
#> 10 x 10 sparse Matrix of class "dgCMatrix"
#> [[ suppressing 10 column names ‘a’, ‘b’, ‘c’ ... ]]
#>
#> a . 0.4678542 0.9239261 . . . .
#> b 0.4678542 . 0.3161797 . . . .
#> c 0.9239261 0.3161797 . . . . .
#> d . . . . . . .
#> e . . . . . . .
#> f . . . . . . .
#> g . . . . . . .
#> h . 0.8231206 . 0.7820306 0.8823195 0.3621016 0.8196023
#> i . . . 0.2665549 0.2042925 . .
#> j . . . . . . .
#>
#> a . . .
#> b 0.8231206 . .
#> c . . .
#> d 0.7820306 0.2665549 .
#> e 0.8823195 0.2042925 .
#> f 0.3621016 . .
#> g 0.8196023 . .
#> h . . 0.8312953
#> i . . .
#> j 0.8312953 . .