s-news
[Top] [All Lists]

Re: Find first consecutive pair in vector

To: "Mario Cortina Borja" <M.Cortina@ich.ucl.ac.uk>, "Potgieter, Andries B" <Andries.Potgieter@dpi.qld.gov.au>
Subject: Re: Find first consecutive pair in vector
From: "Biggerstaff, Brad J." <bkb5@cdc.gov>
Date: Thu, 7 Jul 2005 09:41:18 -0600
Cc: <s-news@lists.biostat.wustl.edu>
Thread-index: AcWCx9y1FXT7L9hgS+KDmpJpbvBQNwAQgtRw
Thread-topic: [S] Find first consecutive pair in vector

ind <- which(X > 0 & c(X[-1],0) > 200)[1]    # returns NA if condition not satisfied

X[ind + 0:1]                                            # so is NA if condition not satisfied

 

 

Brad Biggerstaff, Ph.D.
(970) 221-6473 ...
BBiggerstaff@cdc.gov


From: s-news-owner@lists.biostat.wustl.edu [mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Mario Cortina Borja
Sent: Thursday, July 07, 2005 1:55 AM
To: Potgieter, Andries B
Cc: s-news@lists.biostat.wustl.edu
Subject: Re: [S] Find first consecutive pair in vector

 

>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>