# How to detect peaks in a specific range in R

I have a time series and I would like to define (and identify) some peaks, but only for a specific range in R.

```
here is an example
## generate test data with 3 peaks
set.seed(123)
x <- seq(0, 360, length = 20)
y <- abs(rnorm(20, mean = 1, sd = 0.1))
y[5:10] <- c(2, 4, 7, 3, 4, 2)
y <- c(y, 0.8 * y, 1.2 * y)
x <- seq(0, 360, along = y)
y[6] <- y[7] # test case with 2 neighbouring equal points
plot(x, y, type="b")
```

# In this example, let's say I want to select peaks (y) only between 6 and 9 (2 peaks) or only between 2 and 4 (also 2 peaks).

I am aware of several packets in R detection peaks (eg, peaks, pastes, quanta, pracma, splus2R), but none of them have this feature, usually only have a minimum threshold.

Any advice would be appreciated.

Thank you

Martin

Edit: The code Eric provided works great. But with my own datasets, I have a little problem. What would you do to detect only one peak if the same values are twice in a certain window (x). Basically, I would like to create a conditional statement that says that you need a certain number of points (x) between the peaks in order to count as two distinctive peaks.

source to share

Something like this is close (not sure if you want to define a peak with two values twice).

```
# Reproduce your data
set.seed(123)
x <- seq(0, 360, length = 20)
y <- abs(rnorm(20, mean = 1, sd = 0.1))
y[5:10] <- c(2, 4, 7, 3, 4, 2)
y <- c(y, 0.8 * y, 1.2 * y)
x <- seq(0, 360, along = y)
y[6] <- y[7] # test case with 2 neighbouring equal points
plot(x, y, type="b")
# shift y up and down a position (for peak identification)
yu <- c(tail(y, -1), NA)
yd <- c(NA, head(y, -1))
# identify peaks that are in the correct range
# where y is higher than the point before and after
high <- which(y - yu >= 0 & y - yd >= 0 & y > 6 & y < 9)
low <- which(y - yu >= 0 & y - yd >= 0 & y >= 2 & y <= 4) # one peak is at 4
# plot lines at peaks
abline(v = x[high], col = 'blue')
abline(v = x[low], col = 'red')
```

source to share