0

I have a list of binary coded observations regarding whether one entity is present or absent at one given time, e.g.,

date       a b c d e f g 
07-07-2021 0 1 1 0 0 0 0
07-08-2021 1 0 0 0 1 1 1
07-10-2021 0 0 1 1 1 1 0
07-11-2021 1 1 1 0 0 1 1

I have created a network object from a co-occurrence matrix calculated by using crossprod(). I would like to add the observation date to the network as an edge attribute, but I'm not sure how to do that. I'm wondering how I can achieve my goal using R package(s). Thank you!

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81

1 Answers1

0

This is a very inelegant solution and I'm sure someone smarter than me could do better. Call it the brute force approach. The basic idea is that rather than using crossprod() to get a single adjacency matrix, create separate adjacency matrices for every date. You can do this by turning the initial data into a matrix that replicates each row by the size of the data, and then multiplying by the transpose of itself. Then turn each adjacency matrix into an edgelist and add the date as an attribute of every edge. Then combine all the edgelists into one. Create an igraph object from the edgelist. Then add the dates as an edge attribute (as far as I know, igraph requires that you do these last two as separate steps). I told you it was inelegant.

library(igraph)

dates <- paste("day",1:4) # I simplified the dates

data <-matrix(c(0,1,1,0,0,0,0,1,0,0,0,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0,1,1),
               ncol = 7, nrow = 4, byrow =T) # your data
colnames(data) <- letters[1:7]
rownames(data) <- dates

data <- as.data.frame(t(data)) # turn the data on its side

edgelists <- mapply(function(x, dates){
  m <- matrix(x,nrow = length(x), ncol = length(x)) #turn each ROW of original data (now each COLUMN) into a matrix
  rownames(m) <- colnames(m) <- rownames(data) # it will help to keep track of the names
  n <- as.data.frame(as_edgelist(graph_from_adjacency_matrix(m*t(m)))) #create adjacency matrix and then turn it back into an edgelist
  n$date <- dates # asign date
  return(n)
  },
  x = data,
  dates = as.list(dates),
  SIMPLIFY =F) 

el <- do.call("rbind", edgelists) # combine all edgelists into one

ig <- graph_from_edgelist(as.matrix(el[,1:2])) # make igraph object
E(ig)$date <- el$date # add the date as edge attribute
plot(ig, edge.label = E(ig)$date)) #check result
tvg
  • 388
  • 2
  • 13