我如何创建一个新矩阵,其中包含来自另一个矩阵的非 NA 值以及它们所在的行和列?

How can i create a new matrix with the non NA values from another matrix and the row and column they were found in?

我有一个名为 n x n 的矩阵 d ,其中大部分填充了 NA值,但有一些随机值分布在各处。

我需要创建一个名为 ds 的新矩阵,其中包含名为 headtail[=48= 的三列] 和 weight,其中 weight 是在矩阵 d 中找到的值,并且 headtail 分别是 d 的行和列,其中 weight 被发现。

矩阵d:

n = 1000 
d = runif(n*n) 
d[d < 0.80] = NA 
d = matrix(d,nrow=n,ncol=n) #reshape the vector 
diag(d) = NA # no self-loops 
d[upper.tri(d)] = t(d)[upper.tri(d)] # undirected graphs are symmetric

str(d)
num [1:1000, 1:1000] NA NA NA 0.861 NA ...

str(ds)head(ds) 的期望输出:

str(ds) 
num [1:99858, 1:3] 1 1 1 1 1 1 1 1 1 1 ... 
- attr(*, "dimnames")=List of 2 
..$ : NULL 
..$ : chr [1:3] "head" "tail" "weight" 

head(ds) 
     head tail    weight 
[1,]    1   15 0.9205357 
[2,]    1   16 0.9938016 
[3,]    1   29 0.9480700

上面矩阵中 return 的实际值并不重要,因为它们是随机生成的,但我的最终输出应该看起来相似。

我尝试过的:

head = c()
tail = c()
weight = c()
for (i in 1:n)
  for (j in 1:n)
    if (is.na(d[i][j]) == FALSE)
      head[i] = i
      tail[i] = j
      weight[i] = d[i][j]
ds = cbind(head, tail, weight)

但是,这会导致以下结果:

str(ds)
 num [1:1000, 1:3] NA NA 3 NA NA NA NA NA NA NA ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "head" "tail" "weight"

head(ds)
     head tail weight
[1,]   NA   NA     NA
[2,]   NA   NA     NA
[3,]    3   NA     NA
[4,]   NA   NA     NA
[5,]   NA   NA     NA
[6,]   NA   NA     NA

同样,我如何在矩阵 d 中搜索非 NA 值,并在找到它们时更新矩阵 ds它所在的行、所在的列以及值本身?

我们可以使用两个很好的 R 技巧来处理矩阵:which(arr.ind = TRUE)[ 中的矩阵索引。下面我只修改了您的设置代码以添加可重复性的种子并制作 n 10 这样您就可以看到所有元素并说服自己这是在做它应该做的事情。

首先我们使用which到return矩阵d中非NA行和列索引的矩阵。使用 arr.ind = TRUE,我们为输入的每个维度保留一个索引,而不是在索引之前展平为一个向量。其次,我们将索引与通过将该索引矩阵传递给 [ 获得的相应权重的向量进行列绑定。您可以直观地比较 dout 并看到值对齐。

set.seed(1)
n = 10 
d = runif(n*n) 
d[d < 0.80] = NA 
d = matrix(d,nrow=n,ncol=n) #reshape the vector 
diag(d) = NA # no self-loops 
d[upper.tri(d)] = t(d)[upper.tri(d)]

indices <- which(!is.na(d), arr.ind = TRUE)
out <- cbind(indices, d[indices])
colnames(out) <- c("head", "tail", "weight")
head(out)
#>      head tail    weight
#> [1,]    4    1 0.9082078
#> [2,]    6    1 0.8983897
#> [3,]    7    1 0.9446753
#> [4,]    8    2 0.9919061
#> [5,]    9    3 0.8696908
#> [6,]    1    4 0.9082078

reprex package (v0.3.0)

于 2019-09-24 创建