【问题标题】:How can i create a new matrix with the non NA values from another matrix and the row and column they were found in?如何使用来自另一个矩阵的非 NA 值以及它们所在的行和列创建一个新矩阵?
【发布时间】:2019-09-24 17:46:04
【问题描述】:

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

我需要创建一个名为 ds 的新矩阵,其中包含三个名为 headtailweight 的列,其中 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

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

我尝试过的:

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 for-loop matrix graph adjacency-matrix


    【解决方案1】:

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

    首先我们使用which 来返回矩阵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 年 9 月 24 日创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2019-05-04
      相关资源
      最近更新 更多