[R] Newbie problem: Vectorizing a minimum function with constraints
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Feb 3 01:46:29 CET 2007
Try this:
> x <- c(20, 25, 15, 20)
>
> f <- function(i, x) {
+ out <- which.max(x > x[i] & seq_along(x) > i)
+ if (out == 1) NA else out
+ }
> sapply(seq_along(x), f, x)
[1] 2 NA 4 NA
On 2/2/07, Oliver Faulhaber <oliverfaulhaber at gmx.de> wrote:
> Sorry, if this question is rather basic, but being a newbie I still have
> problems to think in the "R way".
>
> My problem is as follows:
>
> - I have a data frame X with stock prices X$Price and corresponding
> dates X$Date.
>
> - Now I want to get for each date x in X$Date the index z, such that
> z = min (a | X$Date(a)>x and X$Price(a)>Price(x)
>
> To put it simple, I am looking for the first time in the future at which
> the stock price is higher than today's stock price. If such a time does
> not exist the output should be N.A.
>
> An example input:
>
> Index X$Price X$Date
> 1 20 2000-01-01
> 2 25 2000-01-02
> 3 15 2000-01-03
> 4 20 2000-01-04
>
> The output should be
>
> Index z
> 1 2
> 2 N.A.
> 3 4
> 4 N.A.
>
> I don't have any idea how to program this in an elegant way in R. Any
> help is thus highly appreciated.
>
> Thanks in advance
> Oliver
>
> --
> Oliver Faulhaber (Dipl.-Math. oec., Aktuar DAV)
> oliverfaulhaber at gmx.de · www.oliverfaulhaber.de
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list