Nick
Nick

Reputation: 1116

How to restore attribute after union n igraphs?

let's say I have n igraphs objects g1, g2,.., gn. They are undirected and weighted graphs, i.e. new weight's attribute should be added. I'd like to union n graphs into the weighted graph g.

It is known from the documentation (see ?graph.union) if the n graphs have the weight attribute, it is renamed by adding a _1 and _2 (and _3, etc.) suffix, i.e. weight_1, weight_2,..., weight_n.

I have seen the answer and wrote the code for n=3 graphs (see below).

Edited:

library(igraph)

rm(list=ls(all=TRUE)) # delete all objects

g1 <- graph_from_literal(A1-B1-C1)
g2 <- graph_from_literal(A2-B2-C2)
g3 <- graph_from_literal(A3-B3-C3)

E(g1)$weight <- c(1, 2)
E(g2)$weight <- c(3, 4)
E(g3)$weight <- c(5, 6)


g        <- union(g1, g2, g3)

new_attr <- as.list(list.edge.attributes(g))
k        <- length(new_attr) # number of new attributes

value_new_attr <- lapply(list.edge.attributes(g), 
                         function(x) get.edge.attribute(g,x))

df <- data.frame()
for (i in 1:k) {df <- rbind(df, value_new_attr[[i]])}
E(g)$weight <- colSums(df, na.rm=TRUE)

g <- delete_edge_attr(g, "weight_1") # 1
g <- delete_edge_attr(g, "weight_2") # 2
g <- delete_edge_attr(g, "weight_3") # 3

Question. How to rewrite the last tree commands with the lapply() function?

My attempt does not work:

g <- lapply(value_new_attr, function(x) {g <- delete_edge_attr(g, x)})

Upvotes: 2

Views: 299

Answers (1)

Nick
Nick

Reputation: 1116

I have found the solution with for-loop

# delete edge attributes with suffix
for (i in 1:k) {g <- delete_edge_attr(g, new_attr[i])}

Upvotes: 2

Related Questions