Remove NA values from distance matrix in R

Viewed 2054

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. 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!

1 Answers

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. It omits rows and columns that have an NA in the complete distance matrix, i.e., if a node has any missing distances, it is entirely gone. If this isn't what you want, please demonstrate your desired result on a reasonably sized input like this one.

Related