Skip to content
Back to formatted view

Raw Message

Message-ID: <497CEE8D.9030406@comcast.net>
Date: 2009-01-25T22:58:21Z
From: Marc Schwartz
Subject: comparing the previous and next entry of a vector
In-Reply-To: <63CBE05F-D7CA-461E-9F14-B38063131B5A@licht-malerei.de>

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