【发布时间】:2023-01-21 05:13:39
【问题描述】:
我目前有一个矩阵,如下所示:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 2 12 NA NA NA NA
[2,] 1 3 7 13 NA NA
[3,] 2 4 8 14 NA NA
[4,] 3 5 9 15 NA NA
....
....
....
[31870] .... .....
我想要做的是创建一个大小为 31870 x 31870 的邻接矩阵。这个新矩阵的第一行将仅包含零,但第 2 列和第 12 列的零除外。其他行依此类推。理想情况下,该解决方案既快速又灵活,足以处理超过 6 个邻居,并且还可以应用于创建 31870 x 31870 以外的其他维度的矩阵。
我在网上找到了对 ifelse() 函数的引用,但我无法正确实现它。我还尝试循环遍历一个空的二进制矩阵。那也不管用。我还尝试使用关键字“二进制矩阵”、“设计矩阵”和“邻接矩阵”来查找类似的问题。我尝试将我的矩阵转换为边列表,然后将其转换为邻接矩阵。我没有让它工作。
更新
我最终用以下嵌套的 for 循环和 igraph 包解决了这个问题:
# Count the non-NaNs in the matrix
nr_of_entries_adjacencies <- dim(matrix)[1] * dim(matrix)[2]
# Initialize an empty vector to store all adjacencies
init_edge_list <- matrix(data = NaN, nrow = nr_of_entries_adjacencies, ncol = 2)
# My original problem was concerned with finding the number of neighbors to a coordinate. Here I added one extra 'neighbor', which represents the coordinate's distance to itself
nr_of_neighbors_plus_one <- 7
for (row_nr in 1:dim(matrix)[1]) {
print(row_nr)
for (col_nr in 1:dim(matrix)[2]) {
if (is.na(matrix[row_nr,col_nr]) == FALSE) {
edge_list_row_nr <- ((row_nr-1) * nr_of_neighbors_plus_one) + col_nr
init_edge_list[edge_list_row_nr ,2] <- init_row_nan_padded[row_nr, col_nr]
init_edge_list[edge_list_row_nr, 1] <- row_nr
}
}
}
# Remove the rows with Na's
edge_list <- na.omit(init_edge_list)
# Convert to graph dataframe
graph_dataframe <- igraph::graph.data.frame(edge_list)
# Convert to adjacency matrix
adjacency_matrix <- igraph::get.adjacency(graph_dataframe,sparse=TRUE)
【问题讨论】:
-
请提供足够的代码,以便其他人可以更好地理解或重现问题。