Search code examples
rarraysna

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

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