如何在联合n igraph之后恢复属性?

时间:2017-03-25 01:18:50

标签: r for-loop attributes igraph lapply

假设我有n igraphs对象g1g2,..,gn。它们是无向和加权图形,即应添加新的权重属性。我想将n图表合并到加权图g中。

从文档中可以看出(参见?graph.unionn图表是否具有weight属性,通过添加_1和{{1}来重命名}(和_2等)后缀,即_3weight_1,...,weight_2

我看过answer并编写了weight_n图表的代码(见下文)。

编辑:

n=3

问题。如何使用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 函数重写最后一个树命令?

我的尝试不起作用:

lapply()

1 个答案:

答案 0 :(得分:2)

我找到了for-loop

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