NOA11120
NOA11120

Reputation: 27

how to find maximum of series within a vector in R code

I want to get the maximum of each series that is non zero. For example:

x <- c(0, 0, 0, 10, 50, 30, 0, 0, 0, 0, 30, 6, 5, 44, 0, 0, 1, 2)

I want to get 50, 44, 2 in R code.

Upvotes: 1

Views: 61

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You can make use of rle:

zero <- rle(x == 0)
y <- sapply(split(x, rep(seq_along(zero$lengths), zero$lengths)), max)
y[y > 0]
##  2  4  6 
## 50 44  2 

Or, similarly, with "data.table":

library(data.table)
data.table(x)[, max(x), rleid(x == 0)][V1 > 0]
##    rleid V1
## 1:     2 50
## 2:     4 44
## 3:     6  2

Upvotes: 3

Related Questions