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. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.