[R] Avoiding for-loop for splitting vector into subvectors based on positions

2010-05-04 Thread Joris Meys
Dear all, I'm trying to optimize code and want to avoid for-loops as much as possible. I'm applying a calculation on subvectors from a big one, and I get the subvectors by using a vector of starting positions: x - 1:10 pos - c(1,4,7) n - length(x) I try to do something like this : pos2 - c(pos,

Re: [R] Avoiding for-loop for splitting vector into subvectors based on positions

2010-05-04 Thread jim holtman
Try this: x - 1:10 pos - c(1,4,7) pat - rep(seq_along(pos), times=diff(c(pos, length(x) + 1))) split(x, pat) $`1` [1] 1 2 3 $`2` [1] 4 5 6 $`3` [1] 7 8 9 10 On Tue, May 4, 2010 at 11:29 AM, Joris Meys jorism...@gmail.com wrote: Dear all, I'm trying to optimize code and want to avoid

Re: [R] Avoiding for-loop for splitting vector into subvectors based on positions

2010-05-04 Thread Joris Meys
Thanks, works nicely. I have to do some clocking to see how much the improvement is, but I surely learnt again. Attentive readers might have noticed my initial code contains an error. tmp - x[pos2[i]:pos2[i+1]] should be: tmp - x[pos2[i]:(pos2[i+1]-1)] off course... On Tue, May 4, 2010 at 5:50