[R] Selecting the first occurrence of a value after an occurrence of a different value

surreyj surreyjackson at gmail.com
Mon Jan 17 09:40:53 CET 2011


Hi Freddy, 

I have a long column of event codes e.g. below (in multiple files) that I am
trying to analyse.  

OutMag
FirstResp
InMag
MagUp
OutMag
MagDwn
Resp
Resp
Resp
InMag
MagUp
OutMag
InMag
OutMag
InMag
OutMag
InMag
OutMag
InMag
MagDwn
OutMag
Resp
MagUp
InMag
MagDwn
OutMag
Resp
MagUp

With these files I have been using which to select the appropriate event
codes so I can do analysis on timing between events using the time
appropriate time coloumn. 

This has worked well so far and now I am faced with the problem that I need
to select the first "Resp" that occurs after each "MagDwn".  Sometimes there
will be just one "Resp" in between a "MagDwn" and sometimes there will be
many e.g. up to 500.  

This code onlyfirstresponseafterrft<-which(!diff(as.numeric(factor(Stat,
levels = c("MagDwn", "Resp")))))
allowed me to select the first "Resp" (or so I thought) but in the file I
tried it on there were only two occurences of "Resp" inbetween each "MagDwn"
and now that I have tried it on files with more "Resp" it is actually
selecting all but the last one that happens before the "Mag Dwn" but I only
need the first one. 

Hope that makes sense, thanks for your help. 
-- 
View this message in context: http://r.789695.n4.nabble.com/Selecting-the-first-occurrence-of-a-value-after-an-occurrence-of-a-different-value-tp3217340p3220852.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list