From 29418f2da38de8c39ec2a1fb3d445b63f320be40 Mon Sep 17 00:00:00 2001 From: Thomas Bock Date: Fri, 12 Apr 2024 17:10:44 +0200 Subject: [PATCH] Add check for empty network in scale-freeness functions To avoid running into various errors when calculating scale-freeness for an empty network, check if the network is empty before calculating scale-freeness and return `NA` right away if the network is empty. Signed-off-by: Thomas Bock --- util-networks-metrics.R | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/util-networks-metrics.R b/util-networks-metrics.R index 5111ef5e..8fc8c658 100644 --- a/util-networks-metrics.R +++ b/util-networks-metrics.R @@ -217,8 +217,19 @@ metrics.is.smallworld = function(network) { #' @param minimum.number.vertices the minimum number of vertices with which #' a network can be scale free [default: 30] #' -#' @return A dataframe containing the different values, connected to scale-freeness. +#' @return If the network is empty (i.e., has no vertices), \code{NA}. +#' Otherwise, a dataframe containing the different values, connected to scale-freeness. metrics.scale.freeness = function(network, minimum.number.vertices = 30) { + + ## check whether the network is empty, i.e., if it has no vertices + if (igraph::vcount(network) == 0) { + ## print user warning instead of igraph error + logging::logwarn("The input network has no vertices. Will return NA right away.") + + ## cancel the execution and return NA + return(NA) + } + v.degree = sort(igraph::degree(network, mode = "total"), decreasing = TRUE) ## Power-law fiting @@ -263,10 +274,15 @@ metrics.scale.freeness = function(network, minimum.number.vertices = 30) { #' a network can be scale free [default: 30] #' #' @return \code{TRUE}, if the network is scale free, -#' \code{FALSE}, otherwise. +#' \code{FALSE}, if it is not scale free, +#' \code{NA}, if the network is empty (i.e., has no vertices). metrics.is.scale.free = function(network, minimum.number.vertices = 30) { df = metrics.scale.freeness(network, minimum.number.vertices) - return(df[["KS.p"]] >= 0.05) + if (is.single.na(df)) { + return(NA) + } else { + return(df[["KS.p"]] >= 0.05) + } } #' Calculate the hierarchy values for a network, i.e., the vertex degrees and the local