Sort and subset neighbors by edge property in R using igraph

Using igraphin R, for some node x, I would like to specify the three top neighboring nodes based on the edge property between xand the neighboring node.

Create a focused weighted sample graph:

set.seed(42)
library(igraph)
n <- 10
adjm <- matrix(sample(0:100, n*10), nc=n)
colnames(adjm) <- rownames(adjm) <- letters[1:n]
g <- graph.adjacency(adjm, weighted=TRUE)

To the top are three outgoing edges for xbased on the edge property (here the weight) on the input adjacency matrix:

x <- 'e'
adjm[x,][order(adjm[x,], decreasing = TRUE)][1:3]

Conclusion:

 i  a  b 
86 62 40 

The current approach is rather cumbersome: select neighbors and edges to neighbors, add to the data frame, sort the data and select three:

x <- 'e'
tab <- data.frame(cbind(
  name=V(g)[neighbors(g,x, mode='out')]$name,
  weight=E(g)[x %->% neighbors(g,x, mode='out')]$weight)) # or %--%, %<-%
tab <- tab[order(tab$weight, decreasing=TRUE),]
head(tab,3)

Conclusion:

  name weight
8    i     86
1    a     62
3    c      6

Is there a more elegant approach?

+4
source share
1 answer

I don't know if this is elegant, but of course, in short:

e_edges <- E(g)[from(x)]
e_top_weights <- order(e_edges$weight, decreasing=TRUE)[1:3]
E(g)[ as.vector(e_edges)[e_top_weights] ]

:

#> [48] e -> i
#> [41] e -> a
#> [42] e -> b

, e_edges , . igraph,

e_edges[e_top_weights]

, , .

+4

All Articles