你好,我有一个数字列表,类似于c(1,2,10,41,42,43,50)。最长连续序列的长度为3,起始数字为41。但是如何在R语言中实现呢?非常感谢!
你好,我有一个数字列表,类似于c(1,2,10,41,42,43,50)。最长连续序列的长度为3,起始数字为41。但是如何在R语言中实现呢?非常感谢!
这里有一个可能的解决方案。
v <- c(1,2,10,41,42,43,50) # Your data
temp <- cumsum(c(1, diff(v) - 1))
temp2 <- rle(temp)
v[which(temp == with(temp2, values[which.max(lengths)]))]
# [1] 41 42 43
一种方法是将向量拆分成其序列,然后取列表中最长的元素。
x <- c(1, 2, 10, 41, 42, 43, 50)
s <- split(x, cumsum(c(TRUE, diff(x) != 1)))
s[[which.max(lengths(s))]]
# [1] 41 42 43