FilipeTeixeira
FilipeTeixeira

Reputation: 1160

Subset graph based on edges weight

I have a graph, G=(V,E) with several attributes including an edge weight attribute. I'm trying to create a subgraph based on a condition where weights are higher than x.

I've tried the standard R subsetting option with g <- E(g)[weight > max(weight)*.10], but I always get a vector. I'm not sure what I'm doing wrong here.

Upvotes: 3

Views: 2322

Answers (2)

Djork
Djork

Reputation: 3369

That would be because you replaced your graph g with just subsetted edges. If you want to remove edges below the threshold weight, you can use:

g_sub <- delete.edges(g, E(g)[weight <= max(weight)*.10])

Upvotes: 1

lukeA
lukeA

Reputation: 54287

Maybe you want something like this

library(igraph)
set.seed(1)
m <- matrix(sample(c(.5, 2, 5), 100, replace=T, prob = c(.6,.3,.1)), nc=10, dimnames = rep(list(letters[1:10]), 2))
g <- graph_from_adjacency_matrix(m, weighted=T, diag=F, mode="undirected")
coords <- layout.auto(g)
par(mfrow = c(1,3))

plot(g, layout=coords, edge.width = E(g)$weight)

s1 <- subgraph.edges(g, E(g)[E(g)$weight>2], del=F)
plot(s1, layout=coords, edge.width = E(s1)$weight)

s2 <- delete_vertices(s1, degree(s1, mode = "in")==0)
plot(s2, layout=coords[V(g)$name%in%V(s2)$name,], edge.width = E(s2)$weight)

enter image description here

Upvotes: 7

Related Questions