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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to