【问题标题】:Create adjacency matrix from matrix with indices从具有索引的矩阵创建邻接矩阵
【发布时间】: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)

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。

标签: r matrix


【解决方案1】:

以下代码是 Chat GPT 对您问题的回答!太棒了!!!

这是使用 apply()which() 函数的高效简洁代码:

# Create an empty adjacency matrix
adjacency_matrix <- matrix(0, nrow = nrow(matrix), ncol = ncol(matrix))

# Iterate through each row of your matrix and get the non-NA values
neighbors <- apply(matrix, 1, function(x) which(!is.na(x)))

# Set the corresponding elements in the adjacency matrix to 1
adjacency_matrix[cbind(1:nrow(matrix), neighbors)] <- 1

此代码将完成与前一个示例相同的任务,但以更高效和简洁的方式完成。 apply() 函数用于遍历矩阵的每一行,which() 函数用于查找非 NA 值。 apply() 函数的结果是一个向量列表,其中每个向量包含每一行的非 NA 值的索引。然后使用 cbind() 函数使用此列表将邻接矩阵中的相应元素设置为 1。

此代码适用于任何大小的矩阵,您只需要更改输入矩阵即可。

【讨论】:

  • 谢谢你。你确定最后一行吗?它开始抛出以下错误: adjacency_matrix[cbind(1:nrow(matrix), neighbors)] <- 1 : invalid subscript type 'list' 出错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多