[R] vector indexing
Duncan Murdoch
murdoch.duncan at gmail.com
Tue Oct 23 13:40:25 CEST 2012
On 12-10-23 5:39 AM, Rui Barradas wrote:
> Hello,
>
> Try the following.
>
> y=c(2,3,5,2,4,6,8,3,6,2,5)
>
> first <- function(x) min(which(x))
> prefix <- function(x, v) x[seq_len(v)]
> suffix <- function(x, v) x[-seq_len(v)]
>
> first(y > 4)
> prefix(y, first(y > 4))
> suffix(y, first(y > 4))
>
Be careful with this: it fails if the condition is FALSE for every
element, e.g.
> first(y > 10)
[1] Inf
Warning message:
In min(which(x)) : no non-missing arguments to min; returning Inf
I don't know if this is possible in the original context, or what the
desired result would be if it happens: but it's something to look out for.
Duncan Murdoch
More information about the R-help
mailing list