R/calculate_node_distances.R

Defines functions meshgrid calculate_node_distances

library(igraph)
library(tidyverse)

#' creates a grid from input array
#' @param x values for x
#' @param y values for y
#' @return matrix of x and y values as grid
#'
meshgrid <- function(x, y = x) {
  if (!is.numeric(x) || !is.numeric(y))
    stop("Arguments 'x' and 'y' must be numeric vectors.")

  x <- c(x); y <- c(y)
  n <- length(x)
  m <- length(y)

  X <- matrix(rep(x, each = m),  nrow = m, ncol = n)
  Y <- matrix(rep(y, times = n), nrow = m, ncol = n)

  return(list(X = X, Y = Y))
}
#' this calculates distance between nodes using the layout of the network
#' @param net the igraph network
#' @param layout the layout. if null kamada.kawai is used by default
#' @return list of edge distances
calculate_node_distances <- function(net,layout=NULL) {
  if(is.null(layout)) layout <- layout.kamada.kawai(net,weights=1-E(net)$weights)
  adj <- get.adjacency(net,'upper',sparse = FALSE)
  xx <- meshgrid(layout[,1])#,head(ly)[,1])
  yy <- meshgrid(layout[,2])
  nodeDistanceEuclid <- sqrt((xx$X-xx$Y)^2+(yy$X-yy$Y)^2)
  nodeDistanceEuclid[t(adj)>0]
}
oacar/pgsNetwork documentation built on Oct. 1, 2019, 9:15 a.m.