这是一个非常不优雅的解决方案,我相信比我更聪明的人可以做得更好。称之为蛮力方法。基本思想是,与其使用 crossprod() 获取单个邻接矩阵,不如为每个日期创建单独的邻接矩阵。您可以通过将初始数据转换为一个矩阵来完成此操作,该矩阵根据数据的大小复制每一行,然后乘以自身的转置。然后将每个邻接矩阵变成一个边列表,并添加日期作为每个边的属性。然后将所有边缘列表合并为一个。从边缘列表创建一个 igraph 对象。然后将日期添加为边缘属性(据我所知,igraph 要求您将最后两个作为单独的步骤执行)。我告诉过你这很不雅。
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