[R] Vectorization instead of loops problem
Gabor Grothendieck
ggrothendieck at gmail.com
Sun Dec 4 16:41:14 CET 2011
On Sun, Dec 4, 2011 at 10:18 AM, Costas Vorlow <costas.vorlow at gmail.com> wrote:
> Hello,
>
> I am having problems vectorizing the following (i/o using a for/next/while
> loop):
>
> I have 2 sequences such as:
>
> x, y
> 1, 30
> 2, -40
> 0, 50
> 0, 25
> 1, -5
> 2, -10
> 1, 5
> 0, 40
>
> etc etc
>
> The first sequence (x) takes integer numbers only: 0, 1, 2
> The sequence y can be anything...
>
> I want to be able to retrieve (in a list if possible) the 3 last values of
> the y sequence before a value of 1 is encountered on the x sequence, i.e:
>
> On line 5 in the above dataset, x is 1 so I need to capture values: 25, 50
> and -40 of the y sequence.
>
> So the outcome (if a list) should look something like:
>
> [1],[25,50,-40]
> [2],[-10,-5,25] # as member #7 of x sequence is 1...
>
> etc. etc.
>
> Can I do the above avoiding for/next or while loops?
> I am not sure I can explain it better. Any help/pointer extremely welcome.
Try this. embed(z, 4) places values 1,2,3,4 of vector z in the first
row, values 2,3,4,5 in the second row and so on so we want the rows of
embed(y, 4) for which embed(x, 4) is 1, i.e we want rows of embed(y,
4) for which embed(x, 4)[,1]==1, except the first column can be
suppressed (-1).
> embed(y, 4)[embed(x, 4)[, 1] == 1, -1]
[,1] [,2] [,3]
[1,] 25 50 -40
[2,] -10 -5 25
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list