Reputation: 13
I'm new to R/network analysis, and apologize if this is a stupid question. I'm currently trying to convert an edgelist into a network matrix, where the shared category of a group indicates the presence of an edge. (ie. 1 if they are in the same group, 0 if they are not... it might also be possible to indicate different numbers depending on the group... 1 for the first, 2 for the second, etc.)
If this helps, here's a sample of my data (I'm working with two data sets, much larger than this):
edgelist:
netherlands, business and human rights
burkina faso, business and human rights
japan, business and human rights
china, civil and political rights
myanmar, civil and political rights
fiji, civil and political rights
netherlands, civil and political rights
japan, civil and political rights
ethiopia, civil society
egypt, civil society
myanmar, civil society
matrix:
burkina faso, china, japan, netherlands, ethiopia, egypt, myanmar, fiji
burkina faso, 0, 1, 1, 0, 0, 0, 0, 0
china 0, 0, 1, 1, 0, 0, 1, 1
japan 1, 1, 0, 1, 0, 0, 1, 1
netherlands 1, 1, 1, 0, 0, 0, 1, 1
ethiopia 0, 0, 0, 0, 0, 1, 1, 0
egypt 0, 0, 0, 0, 1, 0, 1, 0
myanmar 0, 0, 0, 0, 1, 1, 0, 0
fiji 0, 1, 1, 1, 0, 0, 0, 0
etc.
I've tried reshape
and as.integer
but am struggling to know how that might work in my case...
Thanks in advance, everyone.
Upvotes: 1
Views: 292
Reputation: 79238
you could do:
library(igraph)
a <- aggregate(V1~V2,dat,function(x)combn(as.character(x),2,paste0,collapse=","))[2]
as.matrix(as_adj(graph_from_data_frame(read.csv(text=unique(unlist(a)),h=F),F)))
netherlands burkina faso china myanmar fiji ethiopia egypt japan
netherlands 0 1 1 1 1 0 0 1
burkina faso 1 0 0 0 0 0 0 1
china 1 0 0 1 1 0 0 1
myanmar 1 0 1 0 1 1 1 1
fiji 1 0 1 1 0 0 0 1
ethiopia 0 0 0 1 0 0 1 0
egypt 0 0 0 1 0 1 0 0
japan 1 1 1 1 1 0 0 0
If that seems difficult, you could break it down to:
my_f <-function(x) do.call(rbind,combn(as.character(x),2,simplify = F))
a <-unique(do.call(rbind,aggregate(V1~V2,dat,my_f)[,2]))
as.matrix(as_adj(graph_from_edgelist(a)))
DATA:
V1 V2
1 netherlands business and human rights
2 burkina faso business and human rights
3 japan business and human rights
4 china civil and political rights
5 myanmar civil and political rights
6 fiji civil and political rights
7 netherlands civil and political rights
8 japan civil and political rights
9 ethiopia civil society
10 egypt civil society
11 myanmar civil society
Upvotes: 1