[R] peaks

Thomas Lumley
Tue, 28 May 2002 17:03:59 -0000

On Tue, 28 May 2002, Herve Cardot wrote:

> I am looking for a function in R that is  equivalent to the function
> "peaks" in
> Splus. This function  gives the local maxima of a vector.
> I do not find it using the help and I 'm not sure it exits in R.
>

It should be something like

peaks<-function(x, max=TRUE,na.rm=FALSE){
	if (na.rm)
	   omit<-is.na(x)
	else
	   omit<-FALSE
	if (max)
	  rval<-1+which(diff(sign(diff(x[!omit])))<0)
	else
	  rval<-1+which(diff(sign(diff(x[!omit])))>0)
	if (na.rm){
	  rval<-rval+cumsum(omit)[rval]
	}
	rval
}

This version doesn't allow the first or last observation to be a peak
(and if na.rm=FALSE one before or after a NA can't be a peak either),
which is a matter of definition -- I've never used the S-PLUS function so
I don't know what it does. Use max=FALSE to get `valleys'.



	-thomas