[R] complex matrix manipulation question

Berton Gunter gunter.berton at gene.com
Wed Jan 11 18:22:13 CET 2006


I did not see a reply to your question. Did you get one? If not,here's a
solution using a while() loop which should be fast. One could also use
recursion here in a natural way. This solution assumes that there are no
NA's anywhere -- it's a bit trickier if there are NA's in the x column.
Also, I have omitted matrix notation and just assumed x and y are vectors. I
didn't test this exhaustively, so there might be a few fussy details that
still need debugging. The major problem would be that I did not interpret
your question correctly, but I hope I got it right.

i <- 1; k <- 0; n <-length(x); z <- rep(NA,n)
while(i <=  n) {
    xcsum <- xcsum - k
    inew <- which(xcsum > W)[1]
    if(is.na(inew)) break

-- Bert

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Mark Leeds
> Sent: Tuesday, January 10, 2006 5:55 PM
> To: R-Stat Help
> Subject: [R] complex matrix manipulation question
> I've done stuff like this before but
> it's been a while and I'm stuck.
> Suppose I have a matrix with one
> column x and another column y
> and both are numeric and let the
> row index of the matrix be i
> Starting at index i ( i would equal on the first iteration )
> when the cumulative sum of x_i+1 - x_i
> is greater than W = some constant, I want to mark that spot in the
> row, call it  i^* and sum all the values in y between  i and  i^* and
> put that value
> a third column z. Otherwise, the values in the indices of z
> between i and  i^*-1  should be NA.
> Then, start at i^*+1 and do the same thing again.
> and keep doing thisn until I get all the way through the rows
> of the matrix.
> I think this is tricky but I used to do it and I forgot how to.
> If it has to be done using loops, that's okay but
> from previous experience, I don't think looping is necessary.
> Thanks.
>                                       Mark
> **********************************************************************
> This email and any files transmitted with it are 
> confidentia...{{dropped}}
> ______________________________________________
> R-help at 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

More information about the R-help mailing list