s-news
[Top] [All Lists]

Re: Find first consecutive pair in vector

To: "Potgieter, Andries B" <Andries.Potgieter@dpi.qld.gov.au>
Subject: Re: Find first consecutive pair in vector
From: Mario Cortina Borja <M.Cortina@ich.ucl.ac.uk>
Date: Thu, 07 Jul 2005 08:54:42 +0100
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <200507070714.j677E7wG022361@dpi-gw1.dpi.qld.gov.au>
>From: "Potgieter, Andries B" <Andries.Potgieter@dpi.qld.gov.au>
>To: s-news@lists.biostat.wustl.edu
>Date: Thu, 7 Jul 2005 17:13:58 +1000
>Thread-Topic: Find first consecutive pair in vector
>Thread-Index: AcWBiO1/Zpzj19LrRYWOe5KJqHkyfQAAL5/QAE5BvZA=

>Dear s-list

>I want to find the first consecutive pair with the first value >0 and the second value > 200 in the following vector:
>X <- c( 204,   -24,   -33,   433, -1123,   565,   366,  -494,   261,   205,  270,   201)
>So in this case index 6 and 7 will be the first event and 9,10; 10,11 and 11,12 the others. I want only to select the first time this condition occurs in the vector

>Any ideas in how to do it the easy way?


>Thanks
>Andries

Dear Andries,
A function that does that is:

find1<-
function(X, b1 = 0, b2 = 200)
{
        s1 <- 1:(length(X) - 1)
        s2 <- s1 + 1
        res1 <- s1[X[s1] > b1 & X[s2] > b2][1]
        c(res1, res1 + 1)
}

Best wishes, Mario

<Prev in Thread] Current Thread [Next in Thread>