【发布时间】:2011-02-25 00:29:43
【问题描述】:
在一些帮助下,我想出了如何将一个边缘列表(又名adjacency list)转换为一个adjacency matrix. 我想学习如何为大量边缘列表自动执行此操作,然后将生成的邻接矩阵放入列表。
我猜 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
【问题讨论】:
-
我无法理解 myDF 是什么。您可以粘贴 dput(myDF) 的输出以便我们重现您的数据吗?
标签: r social-networking plyr