[R] Vectorization instead of loops problem
Uwe Ligges
ligges at statistik.tu-dortmund.de
Sun Dec 4 16:30:02 CET 2011
On 04.12.2011 16:18, Costas Vorlow 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.
>
> Best regards,
> Costas
>
>
One way is (assuming your data is in a data.frame called dat):
wx <- which(dat$x==1)
result <- lapply(wx[wx > 3], function(x) dat$y[x - (1:3)])
(where lapply is a loop, implicitly).
Uwe Ligges
More information about the R-help
mailing list