[R] Counting zeros in a matrix

Marc Schwartz marc_schwartz at comcast.net
Tue Nov 28 22:34:21 CET 2006


On Tue, 2006-11-28 at 16:20 -0500, Guenther, Cameron wrote:
> Hi All,
> 
> If you could help me with this problem I would greatly appreciate it.
> 
> Suppose I have a matrix A:
> 
> 1 1 1 1 0 1 1 1 1
> 1 1 1 0 1 0 1 0 0
> 1 0 1 0 0 1 0 0 0
> 1 1 0 0 0 0 1 0 0
> 
> I would like, for each row, to sum the number of times a 0 appears in
> front of a 1. So what I would like is to have
>                    Sum
> 1 1 1 1 0 1 1 1 1   1
> 1 1 1 0 1 0 1 0 0   2 
> 1 0 1 0 0 1 0 0 0   2
> 1 1 0 0 0 0 1 0 0   1
> 
> I tried writing a function to do this but am getting mixed up in the
> [i,j] coding.  This is just an example the real matrix is much larger.
> 
> Thanks in advance.

Not fully tested, but how about this:

> mat
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
1    1    1    1    1    0    1    1    1    1
2    1    1    1    0    1    0    1    0    0
3    1    0    1    0    0    1    0    0    0
4    1    1    0    0    0    0    1    0    0


> cbind(mat, colSums(apply(mat, 1, diff) == 1))
  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
1    1    1    1    1    0    1    1    1    1     1
2    1    1    1    0    1    0    1    0    0     2
3    1    0    1    0    0    1    0    0    0     2
4    1    1    0    0    0    0    1    0    0     1

HTH,

Marc Schwartz



More information about the R-help mailing list