简体   繁体   English

从R中的距离矩阵中删除NA值

[英]Remove NA values from distance matrix in R

I am new to R and I am looking for a way how to remove all rows and columns from a distance matrix which contain NA values. 我是R的新手,我正在寻找一种方法,如何从包含NA值的距离矩阵中删除所有行和列。 Here is an example: 这是一个例子:

set.seed(1)

data <- matrix(rpois(n = 400, lambda = 10), nrow = 20, ncol = 20)
rownames(data) <- LETTERS[1:20]
dist_matrix <- dist(data, method = "euclidean")
dist_matrix[sample(1:190, 10)] <- NA

Is there any elegant way to do this? 有什么优雅的方法可以做到这一点吗? Thank you very much! 非常感谢你!

Let's do a smaller example so we can inspect it: 让我们做一个较小的示例,以便我们对其进行检查:

set.seed(1)
n = 7
data <- matrix(rpois(n = n^2, lambda = 10), nrow = n)
rownames(data) <- LETTERS[1:n]
dist_matrix <- dist(data, method = "euclidean")
dist_matrix[sample(1:(n * (n - 1) / 2), 2)] <- NA
dist_matrix
#           A         B         C         D         E         F
# B  9.327379                                                  
# C 11.224972  9.000000                                        
# D 10.630146        NA 10.049876                              
# E 13.674794 13.490738 12.529964        NA                    
# F 12.165525 11.532563 13.490738  7.000000 10.344080          
# G  6.633250 10.908712 10.862780 11.445523 13.601471 12.649111

x = as.matrix(dist_matrix)
x = x[rowSums(is.na(x)) == 0, colSums(is.na(x)) == 0, drop = FALSE]
as.dist(x)
#          A        C        F
# C 11.22497                  
# F 12.16553 13.49074         
# G  6.63325 10.86278 12.64911

You didn't give example output (and it would be impractical for such a large example), so I'm not 100% sure this is what you want. 您没有提供示例输出(对于这么大的示例,这是不切实际的),因此我不确定100%就是您想要的。 It omits rows and columns that have an NA in the complete distance matrix, ie, if a node has any missing distances, it is entirely gone. 它省略了在完整距离矩阵中具有NA行和列,即,如果节点缺少任何距离,则它完全消失了。 If this isn't what you want, please demonstrate your desired result on a reasonably sized input like this one. 如果这不是您想要的,请在像这样的合理大小的输入上展示您想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM