在一些帮助下,我想出了如何将边缘列表(也称为邻接列表)转换为邻接矩阵。 我想学习如何为大量边缘列表自动执行此操作,然后将生成的邻接矩阵放入列表中。
我猜 plyr 是做到这一点的最好方法,但如果你想告诉我如何使用循环来做到这一点,我也将不胜感激。对于好奇的人来说,这些数据代表了不同学校的社交网络。
这是我到目前为止所得到的:
# extract one school edgelist from the dataframe
aSchool <- myDF[which(myDF$school==1), c("school", "id", "x1","x2","x3","x4","x5","x6","x7","x8","x9","x10")]
# figure out unique ids
edgeColumns <- c("x1","x2","x3","x4","x5","x6","x7","x8","x9","x10")
ids <- unique(unlist(aSchool[edgeColumns]))
ids <- ids[!is.na(ids)]
# make an empty matrix
m <- matrix(0,nrow=length(ids),ncol=length(ids))
rownames(m) <- colnames(m) <- as.character(ids)
# fill in the matrix
for(col in edgeColumns){
theseEdges <- aSchool[c("id",col)]
theseEdges <- na.omit(theseEdges)
theseEdges <- apply(theseEdges,1,as.character)
theseEdges <- t(theseEdges)
m[theseEdges] <- m[theseEdges] + 1
}
for(i in 1:nrow(m)) m[i,i] <- 0