Reputation: 67
How can I transform a edge list to a adjacency matrix in R?
Input is as followed:
from to
Kanye West Jay-Z
Beyonce Nicki Minaj
Kid Cudi Chance The Rapper
Upvotes: 1
Views: 212
Reputation: 50668
Here are two different possibilities:
Using igraph::get.adjacency
# Convert data.frame to igraph
library(igraph);
ig <- graph_from_data_frame(df);
# Get adjacency matrix
get.adjacency(ig);
#6 x 6 sparse Matrix of class "dgCMatrix"
# Kanye West Beyonce Kid Cudi Jay-Z Nicki Minaj
#Kanye West . . . 1 .
#Beyonce . . . . 1
#Kid Cudi . . . . .
#Jay-Z . . . . .
#Nicki Minaj . . . . .
#Chance The Rapper . . . . .
# Chance The Rapper
#Kanye West .
#Beyonce .
#Kid Cudi 1
#Jay-Z .
#Nicki Minaj .
#Chance The Rapper .
Using reshape2::dcast
library(reshape2);
df$from <- factor(df$from, levels = unique(as.character(unlist(df))))
df$to <- factor(df$to, levels = unique(as.character(unlist(df))))
dcast(df, from ~ to, fun.aggregate = length, drop = F);
# from Kanye West Beyonce Kid Cudi Jay-Z Nicki Minaj
#1 Kanye West 0 0 0 1 0
#2 Beyonce 0 0 0 0 1
#3 Kid Cudi 0 0 0 0 0
#4 Jay-Z 0 0 0 0 0
#5 Nicki Minaj 0 0 0 0 0
#6 Chance The Rapper 0 0 0 0 0
# Chance The Rapper
#1 0
#2 0
#3 1
#4 0
#5 0
#6 0
# Sample data
df <- read.table(text =
"from to
'Kanye West' 'Jay-Z'
'Beyonce' 'Nicki Minaj'
'Kid Cudi' 'Chance The Rapper'", header = T)
Upvotes: 1