[S] How to Avoid An Splus Loop Question

andrey@utstat.toronto.edu
Fri, 19 Jun 98 12:11 EDT


>
>In the example below I would like to calculate for each Day within each
>Month the minimum Price that occurred on or after that Day within that
>Month. A loopless solution, anyone?
>
> | DESIRED RESULT
>Month Day Price | MinPrice
> |
> 1 25 45 | 45
> 1 26 50 | 48
> 1 29 48 | 48
> 1 30 49 | 49
>
> 2 29 50 | 50
> 2 30 52 | 51
> 2 31 51 | 51
>
>Allen Humbolt
>

this problem was just too nice for me to resist trying!
here is one, admittedly somewhat hasty, basic idea.
say m, d, and p are the names of the three vectors (say) that you
mention. suppose also that the months are labelled in the manner:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,...
(if they are labelled instead as:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3,...
the idea below can be adjusted by incorporating a dates variable also...)
suppose also, for example, that 10^5 is larger than any of the prices.

## add `factors' assuring no LATER month has lower prices:
x _ p + m*10^5
## next, append 31 large numbers to the end of this vector:
x _ c ( x, rep( (max(m)+1)*10^5, 31) )
n _ length(x)

## now, a somewhat long (but finite!) line of code:
x _ apply (
rbind ( x[1:(n-31)], x[2:(n-30)], x[3:(n-29)], ...etc..., x[31:(n-1)] ),
1,
min )

x _ x - m*10^5 ## now get rid of the added `factors'

x should contain what you want.

i have not had time to check this code (sorry!!), so there are likely
to be small mistakes in it, but believe that the basic idea should work...

andrey feuerverger
university of toronto

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news