Longest Consecutive Subsequence

I need to find the longest consecutive subsequence of a vector, and if there are more than 1 subsequence have the same longest length, I need the last one. My code is as below:

x <- c(1, 3, 7, 11, 40:50, 90:100, 110:115)
seq_blocks <- split(x, cumsum(c(TRUE, diff(x) != 1)))
seq_longest <- seq_blocks[[which.max(lengths(seq_blocks))]]

This code seem to pick up the first longest subsequence, but I need the last one.

You could sort the lengths, which will put the last appearance of the longest length at the end. Then reverse the order and select the name of the first element to get the desired list element.

seq_blocks[names(rev(sort(lengths(seq_blocks))))[1]]

$`6`
 [1]  90  91  92  93  94  95  96  97  98  99 100

You could also select all sequences of maximum length and use tail to get the last one, or dplyr::last if you only want the unlisted vector:

tail(seq_blocks[lengths(seq_blocks) == max(lengths(seq_blocks))], 1)
dplyr::last(seq_blocks[lengths(seq_blocks) == max(lengths(seq_blocks))])
3 Likes

thanks so much. !!!!!!!!!!!!!!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.