生成循环以在R中创建igraph对象列表

生成循环以在R中创建igraph对象列表,r,social-networking,igraph,R,Social Networking,Igraph,我想创建一个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

我想创建一个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)

netEdges由于您提供的代码不是完全可复制的,因此无法保证运行以下内容。它的目的是指导如何构建真正的解决方案。如果您提供其他人可以用来运行代码的示例数据,您将得到更好的答案

最简单的方法可能是将
net
拆分为一个列表,每个
community
的唯一值对应一个元素,然后将图形构建代码应用于每个片段,将每个片段的结果存储在另一个列表中。在R中有几种方法可以完成这类工作,其中之一就是使用
lappy

#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)
#基于社区独特的价值观将网络分割成碎片

netSplit由于您提供的代码不是完全可复制的,因此不能保证运行下面的代码。它的目的是指导如何构建真正的解决方案。如果您提供其他人可以用来运行代码的示例数据,您将得到更好的答案

最简单的方法可能是将
net
拆分为一个列表,每个
community
的唯一值对应一个元素,然后将图形构建代码应用于每个片段,将每个片段的结果存储在另一个列表中。在R中有几种方法可以完成这类工作,其中之一就是使用
lappy

#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)
#基于社区独特的价值观将网络分割成碎片

你能详细谈谈你的问题吗?提供数据样本将帮助人们回答您的问题。您可以对数据集使用dput(),也可以创建一个小的虚拟集来测试代码。另外,除非我遗漏了什么,否则我看不出“净$community”在哪里?你能详细回答你的问题吗?提供数据样本将帮助人们回答您的问题。您可以对数据集使用dput(),也可以创建一个小的虚拟集来测试代码。另外,除非我遗漏了什么,否则我看不到“净$community”在哪里?