Skip to content
Prev 168195 / 398502 Next

comparing the previous and next entry of a vector

on 01/25/2009 04:29 PM J?rg Gro? wrote:
How about this:

InBetween <- function(x, val1, val2)
{
  unlist(sapply(2:(length(x) - 1),
         function(i) if ((x[i - 1] == val1) & (x[i + 1] == val2)) x[i]))
}
[1] 2
[1] 5

It will return NULL if not found.

You might want to reinforce it with some error checking as well.

HTH,

Marc Schwartz