3
votes

I have U.S. trade data between cities. I have attribute data on both the cities (nodes) and the trade (edges).

Consider the following graph:

library(igraph)
gg <- graph.atlas(711)
V(gg)$name <- 1:7
V(gg)$city <- c("BOISE","NEW YORK","NEW YORK","BOISE","BOISE","LA","LA")
V(gg)$color <- ifelse(V(gg)$city=="BOISE", "orange","yellow")
gg <- delete.edges(gg, E(gg,P=c(1,2,2,3,2,7,7,6,7,3,3,4,3,5,4,5,5,6,6,1))) 
gg <- add.edges(gg,c(1,4,4,5,5,1),attr=list(trade=1))
gg <- add.edges(gg,c(7,5,5,4,4,7),attr=list(trade=2))
gg <- add.edges(gg,c(7,3,3,5,5,7),attr=list(trade=3))
gg <- add.edges(gg,c(2,7,7,6,6,2),attr=list(trade=4))
gg <- add.edges(gg,c(6,4),attr=list(trade=5))
plot(gg, edge.label=E(gg)$trade)

The generates the following:

trade network

From this, I want to export an edgelist that includes the edge attribute to a text file.

For instance:

[CITY 1], [CITY 2], [TRADE]

Any help on how I can do this? It seems easy, but I am really stuck.

1

1 Answers

4
votes

You can extract the edge list and then use that to get the vertrex attributes and combine that with the edge attributes. For example

el <- as_edgelist(gg)
data.frame(city1=V(gg)[el[,1]]$city, 
    city2=V(gg)[el[,2]]$city, 
    trade=E(gg)$trade)

#       city1 city2 trade
# 1     BOISE BOISE     1
# 2     BOISE BOISE     1
# 3     BOISE BOISE     1
# 4     BOISE    LA     2
# 5     BOISE BOISE     2
# 6     BOISE    LA     2
# 7  NEW YORK    LA     3
# 8  NEW YORK BOISE     3
# 9     BOISE    LA     3
# 10 NEW YORK    LA     4
# 11       LA    LA     4
# 12 NEW YORK    LA     4
# 13    BOISE    LA     5

The data looks a bit odd because you have multiple vertices with the same city name. Not sure if that was your intention or not.