Networking: creating a graph object from an event - Node Data using igraph
I want to make a network object for an igraph from event note data.
For example, I have data similar to this.
Event Person
1 Obama
1 Putin
1 Abe
1 Cameron
2 Putin
2 Xi
2 Merkel
3 Obama
3 Abe
3 Xi
3 Merkel
I am assuming everyone has connections in the same case. Obama, Putin, Abe and Cameron have connections because they are all in the first case. Based on this data, Obama and Abe have two connections because they are both in case 1 and 3.
With this data, I want to calculate the degree / internecine / closeness. In order to calculate these centralities, I need to have a graph object. How can I create a graph object or adjacency matrix to calculate the three centrality scores?
I am sorry for this basic question, but I am new to using R for network analysis.
Thank you in advance!
source to share
Assuming you are reading your data into a data.frame with a name dd
, you can get a neighboring matrix with
X <- with(dd, table(Event, Person))
adj <- crossprod(X,X)
# Person
# Person Abe Cameron Merkel Obama Putin Xi
# Abe 2 1 1 2 1 1
# Cameron 1 1 0 1 1 0
# Merkel 1 0 2 1 1 2
# Obama 2 1 1 2 1 1
# Putin 1 1 1 1 2 1
# Xi 1 0 2 1 1 2
You have several options for how you want to turn this into a graph object, but most likely use graph.adjacency
. Here's one way
gg<-graph.adjacency(adj, mode="upper", weighted=TRUE, diag=FALSE);
plot(gg, edge.width=E(gg)$weight)
source to share
This is a bipartite graph and you want a projection of it.
txt <- "Event Person
1 Obama
1 Putin
1 Abe
1 Cameron
2 Putin
2 Xi
2 Merkel
3 Obama
3 Abe
3 Xi
3 Merkel
"
data <- read.table(textConnection(txt), header = TRUE)
BG <- graph.data.frame(data, directed = FALSE)
V(BG)$type <- grepl("^[0-9]+$", V(BG)$name)
bipartite.projection(BG)[[1]]
#> IGRAPH UNW- 6 13 --
#> + attr: name (v/c), weight (e/n)
#> + edges (vertex names):
#> [1] Obama--Putin Obama--Abe Obama--Cameron Obama--Xi Obama--Merkel
#> [6] Putin--Abe Putin--Cameron Putin--Xi Putin--Merkel Abe --Cameron
#> [11] Abe --Xi Abe --Merkel Xi --Merkel
source to share