我有一个像下面这样的矩阵
m <- expand.grid(LETTERS[1:24],LETTERS[1:24])
m$weight <- runif(nrow(m), 0.01, max = 1)
m <- m[m$Var1!=m$Var2, ] ##remove loop edges
colnames(m) = c("to","from","weight")
并以这种形式描述了一个有向图。我想要做的是减去并取每对逆边的绝对值,并创建一个描述新无向图的新矩阵。 IE:
abs( edge_weight(A,B) - edge_weight(B,A) )
但我不知道如何只考虑每对一次。
最佳答案
使用 igraph
library(igraph)
#dataframe to directed graph
directed_graph <- graph.data.frame(m, directed = T)
#convert to undirected graph by applying desired function
undirected_graph <- as.undirected(directed_graph, mode = "collapse",
edge.attr.comb = list(weight = function(x) abs(x[1] - x[2])))
#final result
df <- as.data.frame(cbind(get.edgelist(undirected_graph),
unlist(get.edge.attribute(undirected_graph))))
colnames(df) <- c("edge1", "edge2", "weight")
rownames(df) <- NULL
这使
> head(df)
edge1 edge2 weight
1 B C 0.310624073725194
2 B D 0.587582074650563
3 C D 0.0327853348944336
4 B E 0.19360910307616
5 C E 0.328824346032925
6 D E 0.13037203295622
样本数据:
set.seed(123)
m <- expand.grid(LETTERS[1:24], LETTERS[1:24])
m$weight <- runif(nrow(m), 0.01, max = 1)
m <- m[m$Var1 != m$Var2, ]
colnames(m) <- c("to", "from", "weight")
关于r - 找到反向边并从它的相反方向减去它的权重,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51167671/