考虑一个3 x 3 x 3立方体,其中27个元素中的每一个都沿着面连接到其他元素。立方体形状的元件具有6个侧面,因此每个元件最多可以有6个连接(例如,3×3×3立方体中的最中心元素由6个元素限定,并且具有6个连接)。
然后,让m1
,m2
和m3
分别成为立方体的第一层,第二层和第三层。每个元素的名称是xyz
,其中x
,y
,z
是元素的行号,列号和层号。例如,元素213
位于多维数据集的第二行,第一列和第三层。此元素与其他4个元素相连:其中三个元素(113, 313, 223
),一个元素位于其上方(212
)。
x = 3 # nrow
y = 3 # ncol
z = 3 # nlay
# print each layer as a 2D matrix
for(k in 1:z){
m = paste0(rep(1:x, each=x), rep(1:y, times = y), k)
print(matrix(m, nrow=x, byrow=T))
}
[,1] [,2] [,3]
[1,] "111" "121" "131"
[2,] "211" "221" "231"
[3,] "311" "321" "331"
[,1] [,2] [,3]
[1,] "112" "122" "132"
[2,] "212" "222" "232"
[3,] "312" "322" "332"
[,1] [,2] [,3]
[1,] "113" "123" "133"
[2,] "213" "223" "233"
[3,] "313" "323" "333"
igraph
or a related package for creating either an adjacency matrix OR an edge list for a network like this? I need a solution that scales to any number of rows, columns, and layers. Python solutions are welcome.我手动创建了2D邻接矩阵,其中行和列由下面的c(m1, m2, m3)
给出:
m1 = paste0(rep(1:x, each=x), rep(1:y, times = y), 1)
m2 = paste0(rep(1:x, each=x), rep(1:y, times = y), 2)
m3 = paste0(rep(1:x, each=x), rep(1:y, times = y), 3)
c(m1, m2, m3)
[1] "111" "121" "131" "211" "221" "231" "311" "321" "331" "112" "122" "132" "212" "222" "232" "312" "322" "332"
[19] "113" "123" "133" "213" "223" "233" "313" "323" "333"
对于这个简单的例子,邻接矩阵是稀疏的,沿对角线具有0,并且是对称的。它看起来像这样:
这里是C&P的dput()
并验证。
dput(temp)
structure(c(0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1,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, 0, 0, 0, 0, 1, 0, 1, 0), .Dim = c(27L,
27L), .Dimnames = list(c("111", "121", "131", "211", "221", "231",
"311", "321", "331", "112", "122", "132", "212", "222", "232",
"312", "322", "332", "113", "123", "133", "213", "223", "233",
"313", "323", "333"), c("111", "121", "131", "211", "221", "231",
"311", "321", "331", "112", "122", "132", "212", "222", "232",
"312", "322", "332", "113", "123", "133", "213", "223", "233",
"313", "323", "333")))
当节点之间的曼哈顿距离为1时有一条边,因此您可以在R中使用dist()
来创建邻接矩阵:
cube_mat = expand.grid(
x = 1:3,
y = 1:3,
z = 1:3
)
m_dist = as.matrix(dist(cube_mat[, 1:3], method = "manhattan", diag = TRUE))
# Zero out any distances != 1
m_dist[m_dist != 1] = 0
rownames(m_dist) = paste0(cube_mat$x, cube_mat$y, cube_mat$z)
colnames(m_dist) = paste0(cube_mat$x, cube_mat$y, cube_mat$z)
# Plot of the adjacency matrix (looks reversed because 111 is in the bottom left):
image(m_dist)
如果你想使用qazxsw poi的包函数:
igraph
通常,您可以使用igraph包中的函数在边缘列表,邻接矩阵之间进行操作,还可以使用#adj <- my.adjacency.matrix
as_edgelist(graph.adjacency(adj))
生成图形。这是默认的多维数据集:
plot.igraph
plot.igraph(graph.adjacency(adj))