comparing the previous and next entry of a vector
on 01/25/2009 04:29 PM J?rg Gro? wrote:
Hi, I have a quit abstract problem, hope someone can help me here. I have a vector like this: x <- c(1,2,3,4,5,2,6) x [1] 1 2 3 4 5 2 6 now I want to get the number where the previous number is 1 and the next number is 3 (that is the 2 at the second place) I tried something with tail(x, -1) ... with that, I can check the next number, but how can I check the previous number?
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]))
}
InBetween(x, 1, 3)
[1] 2
InBetween(x, 4, 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