Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find and print out rownames with missing values in matrix with apply in R

I have a matrix with missing values. Now I would like to find the missing values, which I did with this apply command.

missing <- apply(is.na(matrix), 1, which)

It prints me each row name and if there is a missing value or not. But I would like to print only the row names where there are missing values and which ones. So I tried:

 for(i in length(missing) != 0L) {
    print(i)
  }

But this doesn’t seem to work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Create a matrix with some missings

mt <- matrix(sample(c(1:5, NA), 50, replace = TRUE), nrow = 5)

From the question; adjusted object names

miss <- apply(is.na(mt), 1, which)

Detect which entries of miss have length of zero and store
the result as a logical vector

miss_row_lgl <- sapply(miss, \(x) length(x) != 0)

Use logical vector to subset miss

miss[miss_row_lgl]
#> [[1]]
#> [1] 1 7 9
#> 
#> [[2]]
#> [1] 7
#> 
#> [[3]]
#> [1] 6
#> 
#> [[4]]
#> [1] 9
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading