[R] Extracting a row number from a matrix

Marc Schwartz (via MN) mschwartz at mn.rr.com
Tue Aug 1 16:42:47 CEST 2006


On Tue, 2006-08-01 at 07:03 -0700, Kartik Pappu wrote:
> Hi all,
> 
> I have a matrix with each column containing a large number of integers
> (0 and above). in each column beyond a certain row (say row 120 in
> column 1, row 134 in column 2, 142 in column 3...)  there are only
> 0's.  I want to find, for each column the row number of the last row
> which contains a positive integer beyond which there are 10 or more
> 0's.
> 
> so in the following example (single column, but my real data has
> multiple columns) how do I  get the row number of the last row of x
> beyond which there are 10 or more 0's (which in this case is row#100).
> 
> x <- as.matrix(c(rep(seq(1:20),5),rep(0,20)))
> 
> I am still new to R so I was wondering if anyone had a quick fix.
> 
> Thanks
> Kartik

Not fully tested, but something like the following:

x <- as.matrix(c(rep(seq(1:20),5),rep(0,20)))

get.zeros <- function(x)
{
  runs <- rle(x == 0)
  pos <- max(which(runs$values & runs$lengths >= 10))
  sum(runs$lengths[1:(pos - 1)])
}

> apply(x, 2, get.zeros)
[1] 100

See ?rle for getting information about sequences of values in a vector.

HTH,

Marc Schwartz



More information about the R-help mailing list