Commit ef084c72 authored by houyun's avatar houyun
Browse files

improve adjacency_matrix()

parent c782ea9e
Loading
Loading
Loading
Loading
+20 −3
Original line number Diff line number Diff line
@@ -132,12 +132,18 @@ as_tbl_graph.corr.test <- function(x, ...) {
#' @description Can be used to convert a correlation object to adjacency matrix.
#' @param x a correlation object (\code{correlate}, \code{md_tbl}, and so on).
#' @param ... expressions that return a logical value.
#' @param type one of "full", "upper" or "lower", used to extract upper or lower
#' triangular part of a adjacency matrix.
#' @param diag if FALSE (default),  self-edges will be removed.
#' @return a matrix object.
#' @author Hou Yun
#' @rdname adjacency_matrix
#' @export
adjacency_matrix <- function(x, ..., diag = FALSE) {
adjacency_matrix <- function(x,
                             ...,
                             type = "full",
                             diag = FALSE) {
  type <- match.arg(type, c("full", "upper", "lower"))
  if (!inherits(x, "cor_md_tbl") && !inherits(x, "correlate")) {
    clss <- class(x)[1]
    x <- as_md_tbl(x)
@@ -154,10 +160,14 @@ adjacency_matrix <- function(x, ..., diag = FALSE) {
    if (isFALSE(diag) && identical(rnm, cnm)) {
      x <- trim_diag(x)
    }
    if (!identical(type, "full") && identical(rnm, cnm)) {
      x <- do.call(paste0("extract_", type), list(md = x))
    }
    x <- dplyr::filter(x, ...)
    out <- df_to_matrix(x, "r", row_id = ".rownames", col_id = ".colnames",
                        row_names = rnm, col_names = cnm, missing = 0)
  } else {
    out <- x$r
    params <- rlang::enquos(...)
    if (length(params) >= 1) {
      for (ii in seq_along(params)) {
@@ -167,12 +177,19 @@ adjacency_matrix <- function(x, ..., diag = FALSE) {
          id <- id & rlang::eval_tidy(params[[ii]], x)
        }
      }
      x$r[!id] <- 0
      out[!id] <- 0
    }
    out <- x$r

    if (isFALSE(diag) && identical(rownames(out), colnames(out))) {
      diag(out) <- 0
    }
    if (!identical(type, "full") && identical(rownames(out), colnames(out))) {
      .f <- switch (type,
        "upper" = "lower.tri",
        "lower" = "upper.tri"
      )
      out[do.call(.f, list(x = out))] <- 0
    }
  }
  out
}
+4 −1
Original line number Diff line number Diff line
@@ -4,13 +4,16 @@
\alias{adjacency_matrix}
\title{Generate adjacency matrix}
\usage{
adjacency_matrix(x, ..., diag = FALSE)
adjacency_matrix(x, ..., type = "full", diag = FALSE)
}
\arguments{
\item{x}{a correlation object (\code{correlate}, \code{md_tbl}, and so on).}

\item{...}{expressions that return a logical value.}

\item{type}{one of "full", "upper" or "lower", used to extract upper or lower
triangular part of a adjacency matrix.}

\item{diag}{if FALSE (default),  self-edges will be removed.}
}
\value{