由于您提供的代码不是完全可重现的,因此不能保证以下内容可以运行。它旨在作为如何构建真正解决方案的指南。如果您提供其他人可以用来运行您的代码的示例数据,您将获得更好的答案。
最简单的方法可能是拆分net
为一个列表,其中每个唯一值都有一个元素,community
然后将您的图形构建代码应用于每个部分,将每个部分的结果存储在另一个列表中。在 R 中有几种方法可以做这种事情,其中一种是使用lapply
:
#Break net into pieces based on unique values of community
netSplit <- split(net,net$community)
#Define a function to apply to each element of netSplit
myFun <- function(dataPiece){
netEdges <- NULL
for (idi in c("nom1", "nom2", "nom3")) {
netEdge <- dataPiece[c("id", idi)]
names(netEdge) <- c("id", "friendID")
netEdge$weight <- 1
netEdges <- rbind(netEdges, netEdge)
}
g <- graph.data.frame(netEdges, directed=TRUE)
#This will return the graph itself; you could change the function
# to return other values calculated on the graph
g
}
#Apply your function to each subset (piece) of your data:
result <- lapply(netSplit,FUN = myFun)
如果一切顺利,result
应该是一个列表,其中myFun
包含community
. 执行类似任务的其他流行工具包括ddply
包中的plyr
。