[R] comparing the previous and next entry of a vector

(Ted Harding) Ted.Harding at manchester.ac.uk
Sun Jan 25 23:55:16 CET 2009


On 25-Jan-09 22:29:25, 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?

  x  <- c(1,2,3,4,5,2,6)
  x0 <- x[1:(length(x)-2)]
  x1 <- x[3:(length(x))]

  x[which((x0==1)&(x1==3))+1]
# [1] 2

Or, changing the data:

  x  <- c(4,5,1,7,3,2,6,9,8)
  x0 <- x[1:(length(x)-2)]
  x1 <- x[3:(length(x))]
  x[which((x0==1)&(x1==3))+1]
# [1] 7

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 25-Jan-09                                       Time: 22:47:15
------------------------------ XFMail ------------------------------




More information about the R-help mailing list