Remove zero column from an array

Asked

Viewed 137 times

5

I have a three-dimensional array and within 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, by removing

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

1 answer

4


If you need to simply remove elements from the array, you can do the same as 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 (within the array) has only 0. One possibility is to use the 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, when removing the elements, the new array has only 3 matrices, so to speak, as the values in positions 2 and 4 cannot be null or empty.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.