Hello,
Roslina Zakaria wrote > > HI, > > > > I would like to extract data in a specific way. For example, the rainfall > data > > > > 0,0,1.5,0,0, 3,1,2.5,0,0,0,0, 2.3,0,0,0, 2.1,1.4,0,0,0, 3,2,1,0,0,0... > > > > data_1: 1.5, 2.3 ( a single nonzero data between zeros data) > > data_2: 3.1, 2.5, 2.1,1.4 ( two nonzero data between zeros data) > > data_3: 3,1,2.5, 3,2,1 ( three nonzero data between zeros data) > > > > > Thank you so much for any help given. > > > > Roslina > > > [[alternative HTML version deleted]] > > > ______________________________________________ > R-help@ 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. > Your data_2 is wrong, not on the given vector. Anyway, try this, x <- c(0,0,1.5,0,0, 3,1,2.5,0,0,0,0, 2.3,0,0,0, 2.1,1.4,0,0,0, 3,2,1,0,0,0) f.runs <- function(x, run){ z <- rle(x != 0) zz <- cumsum(z$lengths) i <- cbind(zz[z$values & z$lengths == run] - (run - 1), zz[z$values & z$lengths == run]) apply(i, 1, function(j) x[ j[1]:j[2] ]) } f.runs(x, 1) f.runs(x, 2) f.runs(x, 3) Hope this helps, Rui Barradas -- View this message in context: http://r.789695.n4.nabble.com/extract-data-tp4533176p4533288.html Sent from the R help mailing list archive at Nabble.com. ______________________________________________ R-help@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.