From 0666f1fffb718063024351b9ccf3c0885bec4acf Mon Sep 17 00:00:00 2001 From: Claus Hunsen Date: Tue, 15 Jan 2019 13:26:29 +0100 Subject: [PATCH] Fix merging of networks without vertices The function 'merge.networks' is not able to handle networks that have not vertices and also (!) no vertex attributes: The final call to 'igraph::graph.data.frame' results in an error. To fix this, the special case is identified and the list of vertices is adjusted accordingly. A corresponding test is added to the test suite. Additionally, the default case of merging only one network is handled by returning the only network right away. Signed-off-by: Claus Hunsen --- tests/test-networks.R | 10 ++++++++++ util-networks.R | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/tests/test-networks.R b/tests/test-networks.R index 56942880..8cdddbea 100644 --- a/tests/test-networks.R +++ b/tests/test-networks.R @@ -86,6 +86,16 @@ test_that("Merge networks", { ## Merge two empty networks (i.e., no vertices at all) ## + network.empty = igraph::graph.empty(0, directed = TRUE) + #create.empty.network(directed = FALSE) + expect_error(merge.networks(list(network.empty, network.empty)), NA) # expect that no error occurs + expect_true(igraph::vcount(merge.networks(list(network.empty, network.empty))) == 0) # vertices + expect_true(igraph::ecount(merge.networks(list(network.empty, network.empty))) == 0) # edges + + ## + ## Merge two empty networks (i.e., no vertices at all, but with vertex attributes) + ## + network.empty = create.empty.network(directed = FALSE) expect_error(merge.networks(list(network.empty, network.empty)), NA) # expect that no error occurs expect_true(igraph::vcount(merge.networks(list(network.empty, network.empty))) == 0) # vertices diff --git a/util-networks.R b/util-networks.R index aefa8e02..4b61ea49 100644 --- a/util-networks.R +++ b/util-networks.R @@ -1125,6 +1125,11 @@ merge.network.data = function(vertex.data, edge.data) { merge.networks = function(networks) { logging::logdebug("merge.networks: starting.") + if (length(networks) == 1) { + logging::logdebug("Only one network given, so a merge is not necessary.") + return(networks[[1]]) + } + ## list with all vertex data frames vertex.data = lapply(networks, function(network) { return(igraph::as_data_frame(network, what = "vertices")) @@ -1138,6 +1143,11 @@ merge.networks = function(networks) { ## merge all edge and vertex data frames new.network.data = merge.network.data(vertex.data, edge.data) + ## catch case where no vertices (and no vertex attributes) are given + if (ncol(new.network.data[["vertices"]]) == 0) { + new.network.data[["vertices"]] = NULL # igraph::graph.data.frame can handle this + } + ## build whole network form edge and vertex data frame whole.network = igraph::graph.data.frame( new.network.data[["edges"]],