如何将图转换为具有给定类型的稀疏邻接矩阵(“dgCMatrix”除外)

问题描述 投票:0回答:1

如何一步将图转换为稀疏“dgTmatrix”?

library(igraph)
library(Matrix)
g <- make_ring(5)
adj <- as_adjacency_matrix(g, sparse = TRUE)
class(adj)
# [1] "dgCMatrix"
# attr(,"package")
# [1] "Matrix"

如何指定除“dgCMatrix”之外的矩阵类(这似乎是默认值)?

adt <- as(adj, "TsparseMatrix")
class(adt)
# [1] "dgTMatrix"
# attr(,"package")
# [1] "Matrix"
cbind(adt@i, adt@j, adt@x)

我尝试过:

class(as_adj(g, type="both", igraph_opt("dgTMatrix")))
但这会创建一个“dgCMatrix”。

r sparse-matrix igraph adjacency-matrix
1个回答
0
投票

我认为它是硬编码在它的源代码中,你可能无法从里面注释它

get.adjacency.sparse <- function(graph, type = c("both", "upper", "lower"),
                                 attr = NULL, edges = FALSE, names = TRUE) {
  ensure_igraph(graph)

  type <- igraph.match.arg(type)

  vc <- vcount(graph)

  el <- as_edgelist(graph, names = FALSE)
  use.last.ij <- FALSE

  if (edges) {
    value <- seq_len(nrow(el))
    use.last.ij <- TRUE
  } else if (!is.null(attr)) {
    attr <- as.character(attr)
    if (!attr %in% edge_attr_names(graph)) {
      stop("no such edge attribute")
    }
    value <- edge_attr(graph, name = attr)
    if (!is.numeric(value) && !is.logical(value)) {
      stop(
        "Sparse matrices must be either numeric or logical,",
        "and the edge attribute is not"
      )
    }
  } else {
    value <- rep(1, nrow(el))
  }

  if (is_directed(graph)) {
    res <- Matrix::sparseMatrix(dims = c(vc, vc), i = el[, 1], j = el[, 2], x = value, use.last.ij = use.last.ij)
  } else {
    if (type == "upper") {
      ## upper
      res <- Matrix::sparseMatrix(
        dims = c(vc, vc), i = pmin(el[, 1], el[, 2]),
        j = pmax(el[, 1], el[, 2]), x = value, use.last.ij = use.last.ij
      )
    } else if (type == "lower") {
      ## lower
      res <- Matrix::sparseMatrix(
        dims = c(vc, vc), i = pmax(el[, 1], el[, 2]),
        j = pmin(el[, 1], el[, 2]), x = value, use.last.ij = use.last.ij
      )
    } else if (type == "both") {
      ## both
      res <- Matrix::sparseMatrix(
        dims = c(vc, vc), i = pmin(el[, 1], el[, 2]),
        j = pmax(el[, 1], el[, 2]), x = value, symmetric = TRUE, use.last.ij = use.last.ij
      )
      res <- as(res, "generalMatrix")
    }
  }

  if (names && "name" %in% vertex_attr_names(graph)) {
    colnames(res) <- rownames(res) <- V(graph)$name
  }

  res
}
© www.soinside.com 2019 - 2024. All rights reserved.