# Re: [R] finding peaks in a simple dataset with R

From: Marc Kirchner <marc.kirchner_at_iwr.uni-heidelberg.de>
Date: Thu 24 Nov 2005 - 01:33:28 EST

>
> I wonder if we shouldn't polish that a bit and add to R's
> standard 'utils' package.
>

Hm, I figured out there are (at least) two versions out there, one being the "original" idea and a modification.

• Petr Pikal in 2001 (based on Brian Ripley's idea)== peaks <- function(series, span=3) { z <- embed(series, span) result <- max.col(z) == 1 + span %/% 2 result }

versus

• Petr Pikal in 2004 == peaks2<-function(series,span=3) { z <- embed(series, span) s <- span%/%2 v<- max.col(z) == 1 + s result <- c(rep(FALSE,s),v) result <- result[1:(length(result)-s)] result }

Comparison shows
> peaks(c(1,4,1,1,6,1,5,1,1),3)

[1] TRUE FALSE FALSE TRUE FALSE TRUE FALSE which is a logical vector for elements 2:N-1 and

> peaks2(c(1,4,1,1,6,1,5,1,1),3)

[1] FALSE TRUE FALSE FALSE TRUE FALSE TRUE which is a logical vector for elements 1:N-2.

As I would expect to "lose" (span-1)/2 elements on each side of the vector, to me the 2001 version feels more natural.

Also, both "suffer" from being non-deterministic in the multiple-maxima-case (the two 4s here)

> peaks(c(1,4,4,1,6,1,5,1,1),3)

[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE
> peaks(c(1,4,4,1,6,1,5,1,1),3)

[1] TRUE TRUE FALSE TRUE FALSE TRUE FALSE
> peaks(c(1,4,4,1,6,1,5,1,1),3)

[1] FALSE FALSE FALSE TRUE FALSE TRUE FALSE
> peaks(c(1,4,4,1,6,1,5,1,1),3)

[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE which also persits for span > 3 (without the 6 then, of course):

> peaks(c(1,4,4,1,1,1,5,1,1),5)

[1] TRUE FALSE FALSE FALSE TRUE
> peaks(c(1,4,4,1,1,1,5,1,1),5)

[1] FALSE FALSE FALSE FALSE TRUE
> peaks(c(1,4,4,1,1,1,5,1,1),5)

[1] TRUE FALSE FALSE FALSE TRUE This could (should?) be fixed by modifying the call to max.col()

result <- max.col(z, "first") == 1 + span %/% 2;

Just my two cents,
Marc

```--
========================================================
Dipl. Inform. Med. Marc Kirchner
Interdisciplinary Centre for Scientific Computing (IWR)
Multidimensional Image Processing
INF 368
University of Heidelberg
D-69120 Heidelberg
Tel: ++49-6221-54 87 97
Fax: ++49-6221-54 88 50
marc.kirchner@iwr.uni-heidelberg.de

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help