1

我想创建一个 Igraph 对象列表,其中每个 Igraph 对象使用的数据由另一个变量确定。

这就是我创建单个 Igraph 对象的方式

netEdges <- NULL

for (idi in c("nom1", "nom2", "nom3")) {
        netEdge <- net[c("id", idi)]
        names(netEdge) <- c("id", "friendID")
        netEdge$weight <- 1
        netEdges <- rbind(netEdges, netEdge)
    }

g <- graph.data.frame(netEdges, directed=TRUE)

对于net$community我想创建一个新的 Igraph 对象的每个唯一值。然后我想计算每个对象的中心性度量,然后将这些度量带回我的net数据集中。非常感谢您的帮助!

4

1 回答 1

1

由于您提供的代码不是完全可重现的,因此不能保证以下内容可以运行。它旨在作为如何构建真正解决方案的指南。如果您提供其他人可以用来运行您的代码的示例数据,您将获得更好的答案。

最简单的方法可能是拆分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

于 2011-07-27T00:50:31.720 回答