Search code examples
rstringseq

R: go through a sequence of numbers and choose the highest one


I am scrapping data from a website, and in this context, data tidying gets kind of hard.

what I have right now is a string of numbers that go into a sequence, let's say

    a<-c(1,2,3,1,2,3,4,5,1,2,3,4)

The first value that I'm looking for is 3, the second one is 5, and the third one will be 4. So basically, I want to go through the sequence 1:5 and choose the highest value, to have the final output as

    a<-c(3,4,5)

I thought about choosing the maximum values, such as

    a<-sort(a, decreasing = T)
    a<-a[1:3]

But this won't count, cause the final product is:

    [1] 5 4 4

where the small values are discriminated. Any ideas if this could be possible?


Solution

  • sort(unlist(lapply(split(a, cumsum(c(1, diff(a)) != 1)), max), use.names = FALSE))
    #[1] 3 4 5