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

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jan 25 23:42:34 CET 2009


Try this:

> DF <- data.frame(x, nxt = c(tail(x, -1), NA), prv = c(NA, head(x, -1)))
> DF
  x nxt prv
1 1   2  NA
2 2   3   1
3 3   4   2
4 4   5   3
5 5   2   4
6 2   6   5
7 6  NA   2
> subset(DF, nxt == 3 & prv == 1)$x
[1] 2


On Sun, Jan 25, 2009 at 5:29 PM, Jörg Groß <joerg at licht-malerei.de> 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?
>
> ______________________________________________
> R-help at 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.
>




More information about the R-help mailing list