morpheus
morpheus

Reputation: 20330

R code to determine peakedness of a maximum

Given input vector x, let the maximum of x occur at index i in the input vector. I am trying to quantify the peakedness of this maximum and do that I have thought of determining following quantities. I am interested in determining numbers l and r such that:

x[i-l] < x[i-l+1] < ... < x[i-1] < x[i] but x[i-l-1] >= x[i-l]

and similarly:

x[i+r] < x[i+r-1] < ... < x[i+1] < x[i] but x[i+r+1] >= x[i+r]

What would be an efficient way of doing this in R? Also how can I generalize this in R so that if input is a matrix M then above procedure is applied independently to each column of M?

Upvotes: 0

Views: 85

Answers (1)

user31264
user31264

Reputation: 6727

You should play with rle and cumsum of boolean vectors. The following function finds l :

left.peak <- function(x) {
    gt = (x[-1] > x[-length(x)])
    gt.rle = rle(gt)
    sum.rle = cumsum(gt.rle$len * gt.rle$val)
    sum.rle = c(0, sum.rle[-length(sum.rle)])
    c(0, cumsum(gt) - rep(sum.rle, gt.rle$len))
}

to find r, reverse x, call left.peak, then reverse x again.

Upvotes: 1

Related Questions