Search code examples
rigraphdata-exportlongitudinal

Create longitudinal data from a list of igraph objects in R


I'm doing analysis on company networks in R and am trying to export my igraph results into a dataframe.

Here's a reproducible example:

library(igraph)
sample <- data.frame(ID = 1:8, org_ID = c(5,4,1,2,2,2,5,7), mon = c("199801", "199802","199802","199802","199904","199912","200001", "200012"))

create.graphs <- function(df){
g <- graph.data.frame(d = df, directed = TRUE)
g <- simplify(g, remove.multiple = FALSE, remove.loops = TRUE)
E(g)$weight <- count_multiple(g)

#calculate global values
g$centrality <- centralization.degree(g)
#calculate local values
g$indegree <- degree(g, mode = "in",
                   loops = FALSE, normalized = FALSE)

return(g)
}

df.list <- split(sample, sample$mon)
g <- lapply(df.list, create.graphs)

As you can see, I have graphs for multiple months. I want to export this to longitudinal data, where each row represents a month (per ID) and each column represents the corresponding network measures.

So far I've managed to create a data frame, but not how to run it through the list of graphs and put it into a fitting format. An additional problem could be that the graphs have different numbers of nodes (some have around 25, others more than 40), but that should theoretically just be recognised as missing by my regression model.

output <- data.frame(Centrality = g$`199801`$centrality,
        Indegree = g$`199801`$indegree)
output
summary(output)

I tried writing a function similar to the one above for this, but unfortunately to no avail.

Thanks in advance for reading this, any help is greatly appreciated


Solution

  • I wanted to share how I solved it (thanks to Dave2e's suggestion).

    Note that ci$monat defines my time periods in the original data, so one row for each point in time.

    sumarTable <- data.frame(time = unique(ci$monat))
    
    sumarTable$indegree <- lapply(g, function(x){x$indegree})
    sumarTable$outdegree <- lapply(g, function(x){x$outdegree})
    sumarTable$constraint <- lapply(g, function(x){x$constraint})
    

    etc

    edit: in order to export these values, I had to "flatten" the lists:

    sumarTable$indegree <- vapply(sumarTable$indegree, paste, collapse = ", ", character(1L))
    sumarTable$outdegree <- vapply(sumarTable$outdegree, paste, collapse = ", ", character(1L))
    sumarTable$constraint <- vapply(sumarTable$constraint, paste, collapse = ", ", character(1L))