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

Bart Joosen bartjoosen at hotmail.com
Fri Jan 14 12:21:02 CET 2011


Ofcourse you can loop over your data, but a vectorised way:


f.search <- function(x, ref, search) {
  cs <- match(cumsum(x==ref), cumsum(x==ref))
  outp <- suppressWarnings(tapply(x==search,cs, function(x)
min(which(x==1))))
  outp <- outp[outp!=Inf] # To remove the occurences where nothing was found
  return(as.vector(as.numeric(names(outp))+outp - 1))
}

f.search(x, "MagDwn", "Resp")

Good luck

Bart
-- 
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-tp3217340p3217482.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list