[R] Detect numerical series
Carl Witthoft
carl at witthoft.com
Sun Feb 12 00:30:47 CET 2012
This was actually answered a couple times in StackOverflow. Someone and
I indpendently wrote up the following function, stolen directly from the
source for rle().
# extended version of rle to find all sorts of sequences
# if incr=0, this is rle
seqle<- function (x,incr=1)
{
if (!is.vector(x) && !is.list(x))
stop("'x' must be an atomic vector")
n <- length(x)
if (n == 0L)
return(structure(list(lengths = integer(), values = x),
class = "rle"))
y <- x[-1L] != x[-n] +incr
i <- c(which(y | is.na(y)), n)
structure(list(lengths = diff(c(0L, i)), values = x[i]),
class = "rle")
}
<quote>
From: David Winsemius <dwinsemius_at_comcast.net>
Date: Sat, 11 Feb 2012 10:08:17 -0500
On Feb 11, 2012, at 10:01 AM, syrvn wrote:
> Hello,
>
> I am struggling with detecting successive digits in a numerical series
> vector.
>
> Here is an example:
>
> vec <- c(1, 15, 26, 29, 30, 31, 37, 40, 41)
>
> I want to be able to detect 29, 30, 31 and 40, 41.
>
> Then, I would like to delete the successive digits from the vector.
>
> 1, 15, 26, 29, 37, 40
vec[ c(TRUE, !diff(vec) == 1) ]
#[1] 1 15 26 29 37 40
--
Sent from my Cray XK6
"Quidvis recte factum, quamvis humile, praeclarum."
More information about the R-help
mailing list