[R] comparing the previous and next entry of a vector
Gabor Grothendieck
ggrothendieck at gmail.com
Mon Jan 26 00:11:50 CET 2009
The data frame is not essential. I was just trying to keep things tidy.
Try this:
nxt <- c(tail(x, -1), NA)
prv <- c(NA, head(x, -1))
x[nxt == 3 & prv == 1]
On Sun, Jan 25, 2009 at 5:53 PM, Jörg Groß <joerg at licht-malerei.de> wrote:
> is there a way to do that without generating a data.frame?
>
> In my real data, I have a big data.frame and I have to compare over
> different columns...
>
>
> Am 25.01.2009 um 23:42 schrieb Gabor Grothendieck:
>
>> 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.
>>>
>
> ______________________________________________
> 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