# How to create a large weighted network with excel data?

I’ve learnt the way of creating a small weighted network with igraph. E.g., I create a star network with 5 vertices using the following:

g < - make_graph(edges = c(1,2, 1,3, 1,4, 1,5), n=5, directed = FALSE)
E(g)\$weight < - c(1,1,2,2)
plot(g)
strength(g)

However, when I want to create a network with hundreds of vertices, this method seems to be very clumsy since we need to type so many vertices and edges. Thus, we can import network data from excel data (e.g., edge list, adjacency list, adjacency matrices). However, the three lists seem only work in unweighted networks. For example, a “edge list” data set contains only two columns, without information of edge strength.

So, I wonder how do we create a large weighted network with igraph? How should I prepare the Excel data? Thank you!

One ugly solution is to just have your weights in a row, use textjoin (Excel - convert row cells into comma separted list - Stack Overflow) to generate a list of comma separated values and then just paste those in your R file.

Maybe not the elegant solution you hoped for, but could be good enough if it’s not necessary to automate things too much.

Thank you for your answer! Although it’s quite “ugly” as you said, I will try it. Thank you again.

A more elegant approach.

``````library(igraph)
## calculate dataframe
text = "from, to, weight
1, 2, 1
1, 3, 1
1, 4, 2
1, 5, 2
")
## You can create the data with Excel or Calc whenever you prefer,
## and read from csv text file.
df

## convert to graph
g <- graph_from_data_frame(df, vertices=seq(5) )
g <- set_edge_attr(g, "weight", value = df\$weight)
strength(g)

## You also could try a random graph, requires no typing.
set.seed(230913)
n = 5
g <- make_star(5, mode="out")
g <- set_edge_attr(g, "weight", value = runif(ecount(g) ))
g <- set_edge_attr(g, name="label", value=E(g)\$weight)
strength(g)
plot(g)
``````
1 Like

Thank you for your great idea! I wonder whether the following (in italics) means that we need to type all the weighted ties in R, If so, will that be too complicated? Or, is the following exactly the way we prepare data in excel?
text = "from, to, weight

• ``````   1, 2, 1*
``````
• ``````   1, 3, 1*
``````
• ``````   1, 4, 2*
``````
• ``````   1, 5, 2*
``````
• ``````  ")*
``````

## You ca

Input the data in excel and then save as .csv text file.

``````# Any comment here
from, to, weight
1, 2, 1
1, 3, 1
1, 4, 2
1, 5, 2
``````

``````fcsv <- choose.files(default="*.csv", multi = FALSE)