From 4fb31797effa910c204c6476d83d7d9095884573 Mon Sep 17 00:00:00 2001 From: Thomas Lin Pedersen Date: Mon, 15 May 2017 21:15:19 +0200 Subject: [PATCH] Correctly initialise attribute elements In order to avoid conversion of factors attribute elements are initialised prior to assignment if the attribute does not exist or if the assignment is overwriting all elements within that attribute --- R/attributes.R | 6 ++++++ R/interface.R | 14 ++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/R/attributes.R b/R/attributes.R index 5eed848d2df..3b742b8e892 100644 --- a/R/attributes.R +++ b/R/attributes.R @@ -254,6 +254,9 @@ i_set_vertex_attr <- function(graph, name, index=V(graph), value, vc <- vcount(graph) vattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) + if (is.null(vattrs[[name]]) || length(unique(index)) == vc) { + vattrs[[name]] <- value[NA] + } if (single) { vattrs[[name]][[index]] <- value } else { @@ -425,6 +428,9 @@ i_set_edge_attr <- function(graph, name, index=E(graph), value, ec <- ecount(graph) eattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L) + if (is.null(eattrs[[name]]) || length(unique(index)) == ec) { + eattrs[[name]] <- value[NA] + } if (single) { eattrs[[name]][[index]] <- value } else { diff --git a/R/interface.R b/R/interface.R index 9ea1acb5bae..f64075fedbb 100644 --- a/R/interface.R +++ b/R/interface.R @@ -81,7 +81,12 @@ add_edges <- function(graph, edges, ..., attr = list()) { } eattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 4L) - for (i in seq(attrs)) { eattrs[[nam[i]]][idx] <- attrs[[nam[i]]] } + for (i in seq(attrs)) { + if (is.null(eattrs[[nam[i]]])) { + eattrs[[nam[i]]] <- attrs[[nam[i]]][rep(NA, edges.new)] + } + eattrs[[nam[i]]][idx] <- attrs[[nam[i]]] + } .Call(C_R_igraph_mybracket2_set, graph, 9L, 4L, eattrs) } @@ -139,7 +144,12 @@ add_vertices <- function(graph, nv, ..., attr=list()) { } vattrs <- .Call(C_R_igraph_mybracket2, graph, 9L, 3L) - for (i in seq(attrs)) { vattrs[[nam[i]]][idx] <- attrs[[nam[i]]] } + for (i in seq(attrs)) { + if (is.null(vattrs[[nam[i]]])) { + vattrs[[nam[i]]] <- attrs[[nam[i]]][rep(NA, vertices.new)] + } + vattrs[[nam[i]]][idx] <- attrs[[nam[i]]] + } .Call(C_R_igraph_mybracket2_set, graph, 9L, 3L, vattrs) }