Jerry Zhang
Jerry Zhang

Reputation: 1462

Return an equivalent array without the zeroes in R?

I have a one-dimensional and two dimensional array. For the one-dimensional array, I'd like a count of non-zero elements, the indices of the non-zero elements, and a good way to return the same array without the zeroes:

i.e.:

c(0, 0.09017892, 0, 0, 0, 0, 0.01685147, -0.06063455, 0, 0, 0, 0) 

to:

 c(0.09017892,  0.01685147,  -0.06063455)

Similarly, with the two-dimensional array with zeroes, I'd like to return a two-dimensional array without the zeroes:

i.e.

      [,1]        [,2] [,3] [,4] [,5] [,6]        [,7]      [,8] [,9] [,10] [,11] [,12]
 [1,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
 [2,]    0  1.00000000    0    0    0    0 -0.09929266 0.1169883    0     0     0     0
 [3,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
 [4,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
 [5,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
 [6,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
 [7,]    0 -0.09929266    0    0    0    0  1.00000000 0.5697163    0     0     0     0
 [8,]    0  0.11698827    0    0    0    0  0.56971626 1.0000000    0     0     0     0
 [9,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
[10,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
[11,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0
[12,]    0  0.00000000    0    0    0    0  0.00000000 0.0000000    0     0     0     0

to:

            [,1]        [,2]      [,3]
[1,]  1.00000000 -0.09929266 0.1169883
[2,] -0.09929266  1.00000000 0.5697163
[3,]  0.11698827  0.56971626 1.0000000

Upvotes: 0

Views: 32

Answers (1)

nicola
nicola

Reputation: 24490

To extract the non-zero elements:

x[x!=0]

To get the indices:

which(x!=0)

To get the number of nonzero elements:

sum(x!=0)

The two-dimensional array case is unclear. What happens if some elements of rows and columns have both zeroes and nonzero elements? However, in your example:

x[rowSums(x!=0)>0,colSums(x!=0)>0]
#            [,1]        [,2]      [,3]
#[1,]  1.00000000 -0.09929266 0.1169883
#[2,] -0.09929266  1.00000000 0.5697163
#[3,]  0.11698827  0.56971626 1.0000000

Upvotes: 2

Related Questions