# [R] consecutive n values

Berry, Charles ccberry @end|ng |rom he@|th@uc@d@edu
Thu Jun 4 19:27:52 CEST 2020

```Catalin,

> On Jun 4, 2020, at 6:06 AM, Catalin Roibu <catalinroibu using gmail.com> wrote:
>
> Dear R users,
>
> Please help me to detect consecutive n values in R and their interval.
>
>
> rle.seq1<-rle(reco\$extr)
> cbind(rle.seq1\$values)
> index<-any(rle.seq1\$values=="DRY"&rle.seq1\$lengths>=3)
> cumsum(rle.seq1\$lengths)[index]
>
> reco is a data frame with 2 columns (year and values (DRY, WET).
>
> I want to have something like this:
> 1799-1800 - WET - 2
> 1803-1805 - WET - 3
>
> Thank you very much!

Something like:

wd.rle <- rle(reco\$extr)
is.wet <- wd.rle[["values"]]=="WET"
wd.rle[["values"]] <- ifelse(is.wet, cumsum( is.wet ), 0)
wet.list <- split( reco\$year, inverse.rle( wd.rle ) )[ -1 ]
sapply( wet.list[ lengths(wet.list) > 1 ], range)

should get you started.

The last line returns:

:         2    3    6    7    8   12   15   20   21   23
: [1,] 1799 1803 1822 1829 1843 1880 1911 1969 1974 1988
: [2,] 1800 1805 1825 1832 1844 1881 1914 1970 1975 1990

You can use `apply' to further process this to get the desired format for your result.

I assume here that reco\$years are in groups of consecutive 'WET' years.

If there are gaps or other oddities you will need to replace `range' with a function that handles that.

HTH,

Chuck

```