Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find the longest same number in R

Tags:

r

for example I have data like this

x<-c(0,0,1,1,1,1,0,0,1,1,0,1,1,1)

I want find the longest sequence of "1" by considering the start and end position, in this case should be (3,6)

How to do this in R

thanks all

like image 927
lei Avatar asked Mar 17 '23 22:03

lei


1 Answers

Here's an approach that uses seqle from the "cgwtools" package:

library(cgwtools)
y <- seqle(which(x == 1))
z <- which.max(y$lengths)
y$values[z] + (sequence(y$lengths[z]) - 1)
# [1] 3 4 5 6

You can use range if you just wanted the "3" and "6".

seqle "extends rle to find and encode linear sequences".


Here's the answer as a function:

longSeq <- function(invec, range = TRUE) {
  require(cgwtools)
  y <- seqle(which(invec == 1))
  z <- which.max(y$lengths)
  out <- y$values[z] + (sequence(y$lengths[z]) - 1)
  if (isTRUE(range)) range(out) else out
}

Usage would be:

x <- c(0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1)
longSeq(x)
# [1] 3 6
longSeq(x, range = FALSE)
# [1] 3 4 5 6

And, with KFB's example input:

y <- c(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1)
longSeq(y)
# [1]  9 11
like image 56
A5C1D2H2I1M1N2O1R2T1 Avatar answered Mar 20 '23 16:03

A5C1D2H2I1M1N2O1R2T1