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 Cheers -- View this message in context: http://r.789695.n4.nabble.com/Detect-numerical-series-tp4379088p4379088.html Sent from the R help mailing list archive at Nabble.com.
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, 40vec[ c(TRUE, !diff(vec) == 1) ] #[1] 1 15 26 29 37 40> > > Cheers > > -- > View this message in context: http://r.789695.n4.nabble.com/Detect-numerical-series-tp4379088p4379088.html > Sent from the R help mailing list archive at Nabble.com. > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.David Winsemius, MD West Hartford, CT
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."
Seemingly Similar Threads
- filling the matrix row by row in the order from lower to larger elements
- Looking for the name of a certain kind of quantile plot
- Remove specific rows in a matrix/data.frame
- Duplicate elements of a vector
- how to get row name of matrix when result is a vector