开发者

make loop to create list of igraph objects in R

I'd like to create a list of Igraph objects with the data used for each Igraph object determined by another variable.

This is how I create a 开发者_Go百科single Igraph object

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)

For each unique value of net$community I'd like to make a new Igraph object. Then I would like to calculate measures of centrality for each object and then bring those measures back into my net dataset. Many thanks for your help!


Since the code you provide isn't completely reproducible, what follows is not guaranteed to run. It is intended as a guide for how to structure a real solution. If you provide example data that others can use to run your code, you will get better answers.

The simplest way to do this is probably to split net into a list with one element for each unique value of community and then apply your graph building code to each piece, storing the results for each piece in another list. There are several ways to doing this type of thing in R, one of which is to use 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)

If all has gone well, result should be a list containing a graph (or whatever you modified myFun to return) for each unique value of community. Other popular tools for doing similar tasks include ddply from the plyr package.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜