Re: [R] Extracting a row number from a matrix

From: Marc Schwartz (via MN) <mschwartz_at_mn.rr.com>
Date: Wed 02 Aug 2006 - 00:42:47 EST

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



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. Received on Thu Aug 03 02:23:01 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 03 Aug 2006 - 04:16:03 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.