Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weighted graph from a data frame

I have an edgelist that I want to convert it to a weighted graph. I used the below code:

edgelist <- read.table(text = "
V1 v2 weights
A B 1
B C 8
C D 6
D E 9
C F 12
F G 15",header=T)


g<-graph_from_data_frame(edgelist)
g

It makes the weights as an attribute for the edges. However, when I want to check if it is weighted or not means:

is_weighted(g)

It returns me FALSE. How can I change it to TRUE?

like image 932
minoo Avatar asked Jan 27 '23 14:01

minoo


1 Answers

You are very close. If you read the documentation with is_weighted you can read the following:

In igraph edge weights are represented via an edge attribute, called ‘weight’

Now if we change the name of your weights column to weight it will work.

edgelist <- read.table(text = "
V1 v2 weight
                       A B 1
                       B C 8
                       C D 6
                       D E 9
                       C F 12
                       F G 15",header=T)
g <- graph_from_data_frame(edgelist)
is_weighted(g)
[1] TRUE

If for some reason you can't rename your column you can always set the weight manually like this:

# based on the weights column if you can't rename input data.frame
g <- set_edge_attr(g, "weight", value= edgelist$weights)
is_weighted(g)
[1] TRUE
like image 79
phiver Avatar answered Feb 03 '23 07:02

phiver