Re: [R] how to create a sequence to consecutive values

2020-08-31 Thread Stefano Sofia
Thank you both of you. I am studying these solutions. Stefano (oo) --oOO--( )--OOo Stefano Sofia PhD Civil Protection - Marche Region Meteo Section Snow Section Via del Colle Ameno 5 60126 Torrette di Ancona, Ancona Uff: 071 806 7743 E-mail:

Re: [R] how to create a sequence to consecutive values

2020-08-28 Thread Bert Gunter
Actually, I prefer Jeff's use of diff() . Hadn't thought of that. However, note that, unsurprisingly, NA's mess up both: The rle() method fails with an error and the diff() method gives the wrong answer. Cheers, Bert On Fri, Aug 28, 2020 at 8:48 AM Jeff Newmiller wrote: > cumsum is a bit

Re: [R] how to create a sequence to consecutive values

2020-08-28 Thread Jeff Newmiller
cumsum is a bit faster... a <- c( 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 , 0, 1, 1, 0, 1, 1, 1, 0 ) f1 <- function(a) { z <- rle(a) v <- z$values v[v==1] <- seq_along(v[v==1]) ## or use cumsum rep(v,z$lengths) } f2 <- function(a) { v <- cumsum( c( a[1], 1==diff(a) ) ) v[ 0==a ] <-

Re: [R] how to create a sequence to consecutive values

2020-08-28 Thread Stefano Sofia
Thank you! Stefano (oo) --oOO--( )--OOo Stefano Sofia PhD Civil Protection - Marche Region Meteo Section Snow Section Via del Colle Ameno 5 60126 Torrette di Ancona, Ancona Uff: 071 806 7743 E-mail: stefano.so...@regione.marche.it ---Oo-oO

Re: [R] how to create a sequence to consecutive values

2020-08-28 Thread Bert Gunter
Using ?rle > z <- rle(a) > v <- z$values > v[v==1] <- seq_along(v[v==1]) ## or use cumsum < rep(v,z$lengths) [1] 0 0 0 1 1 1 1 0 0 0 0 2 2 0 3 3 3 0 0 Cheers, Bert Bert Gunter "The trouble with having an open mind is that people keep coming along and sticking things into it." -- Opus (aka

[R] how to create a sequence to consecutive values

2020-08-28 Thread Stefano Sofia
Dear R-list users, this is a simple question, I have not been able to find an efficient solution. Given a vector with only 0 or 1 values, I need to give a sequence to the consecutive values of 1: a <- c(0,0,0,1,1,1,1,0,0,0,0,1,1,0,1,1,1,0,0) I should get as result