# Remove column zero from an array

## Question:

I have a three-dimensional array and inside that array 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]` , i.e. removing

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

If you simply need to remove the elements from the array, you can do it the same way you would with vectors or matrices, 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 (inside the array) has only 0. One possibility is to `apply` on 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, when removing the elements, the new array has only 3 arrays, so to speak, as the values ​​in positions 2 and 4 cannot be null or empty.

Scroll to Top