ostionalzax ostionalzax - 23 days ago 14
R Question

Remove layer of array that contains all zeros

I'm trying to remove a layer of an array that contains all zeros. Here's an example:

ii = c(25, 9, 0, 6, 19, 30, 13, 27, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 15, 7, 0, 18, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0, 43, 33, 40, 34, 42)
key = array(ii,dim=c(3,3,5))


The end result would be equivalent to
key[,,-c(2,4)]
or
key[,,c(1,3,5)]
. I saw this question but it can only do one row or column. Is there a way to do an entire layer?

Thanks!

Answer

One idea, making use of the fact that apply can work on any combination of rows (MARGIN = 1), columns (MARGIN = 2) strata (MARGIN = 3) and higher dimensions as well (MARGIN= 4 and greater).

key[,,!apply(key,3,function(x) all(x == 0) )]
#or more simply:
key[,,apply(key,3,function(x) any(x != 0) )]
#or simpler again:
key[,,apply(key != 0, 3, any)]

#, , 1
# 
#     [,1] [,2] [,3]
#[1,]   25    6   13
#[2,]    9   19   27
#[3,]    0   30    4
#
#, , 2
# 
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0   15   18
#[3,]    0    7   16
#
#, , 3
#
#     [,1] [,2] [,3]
#[1,]    0    0   40
#[2,]    0   43   34
#[3,]   39   33   42
Comments