Remove zero column from an array

5

I have a three-dimensional array and inside that array there is another array of zeros and I want to remove it from the larger array. For example,

set.seed(1)
a = rnorm(60)
b = array(a, dim = c(10, 2, 5))
b[, , 4] = matrix(rep(0, 20), ncol = 2)
b[, , 2] = matrix(rep(0, 20), ncol = 2)

The result I want is an array with      a[ , ,1], a[ , ,3], a[ , ,5] , that is, removing

a[ , ,2] and a[ , ,4]

    
asked by anonymous 04.01.2016 / 18:14

1 answer

4

If you simply need to remove elements from the array, you can do the same thing as you would do with vectors or arrays, that is, use the minus sign with the index of the elements you want to remove:

b2 <- b[,,-c(2, 4)]

A more dynamic solution would be to automatically detect which array (within the array) has only 0. One possibility is to use apply in the third dimension and check that all elements are zero:

b3 <- b[,,!apply(b, 3, function(d) all(d == 0))]

Note that both lead to the same result:

> identical(b2, b3)
[1] TRUE

Of course, by removing the elements, the new array has only 3 arrays, so to speak, since the values in positions 2 and 4 can not be null or empty.

    
04.01.2016 / 22:17