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

How to remove NAs in an array

Consider that we have an array:

tmp <- array(c(1, 2, 3, 4,
               NA, NA, NA, NA,
               5, 6, 7, 8), dim = c(2, 2, 3))

> print(tmp)
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA

, , 3

     [,1] [,2]
[1,]    5    7
[2,]    6    8

Here, I want to remove the second matrix with NAs.

When we have a matrix, it is not hart to remove a row with NAs using the complete.cases

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

tmp <- matrix(c(1, 2, NA, NA, 3, 4), ncol = 2, byrow = TRUE)
> print(tmp[complete.cases(tmp), ])
     [,1] [,2]
[1,]    1    2
[2,]    3    4

But, in higher dimensional cases, I have no idea how to remove the NAs

>Solution :

apply across the 3rd dimension, and then subset:

tmp[,,apply(tmp, 3, \(x) !all(is.na(x)) )]
#, , 1
#
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#
#, , 2
#
#     [,1] [,2]
#[1,]    5    7
#[2,]    6    8
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