[R] which.minimums not which.min

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed Mar 15 21:56:23 CET 2006


On Wed, 2006-03-15 at 21:45 +0100, Philippe Grosjean wrote:
> What Fred is looking for is local minima/maxima, also known as turning 
> points, or pits/peaks in a series.  You can look at ?turnpoints in 
> pastecs library.
> 
>  > x <- c(1:4,0:5, 4, 11)
>  > x
>   [1]  1  2  3  4  0  1  2  3  4  5  4 11
>  > tp <- turnpoints(x)
>  > summary(tp)
> Turning points for: x
> 
> nbr observations  : 12
> nbr ex-aequos     : 0
> nbr turning points: 4 (first point is a peak)
> E(p) = 6.666667 Var(p) = 1.811111 (theoretical)
> 
>    point type       proba      info
> 1     4 peak 0.100000000 3.3219281
> 2     5  pit 0.002380952 8.7142455
> 3    10 peak 0.005952381 7.3923174
> 4    11  pit 0.666666667 0.5849625
>  > plot(tp) # Only useful for a longer and more complex series!
>  > # Get the position of peaks
>  > (1:length(x))[extract(tp, no.tp = FALSE, peak = TRUE, pit = FALSE)]
> [1]  4 10
> Warning message:
> arguments after the first two are ignored in: UseMethod("extract", e, n, 
> ...)
>  > (1:length(x))[extract(tp, no.tp = FALSE, peak = FALSE, pit = TRUE)]
> [1]  5 11
> Warning message:
> arguments after the first two are ignored in: UseMethod("extract", e, n, 
> ...)
>  > # By the way, there are warnings although it works well (I ask on R-Help)
> 
> Now, you can easily code your which.minima() function using turnpoints:
> 
> x <- c(1:4,0:5, 4, 11)
> x
> tp <- turnpoints(x)
> summary(tp)
> plot(tp) # Only useful for a longer and more complex series!
> # Get the position of peaks
> (1:length(x))[extract(tp, no.tp = FALSE, peak = TRUE, pit = FALSE)]
> (1:length(x))[extract(tp, no.tp = FALSE, peak = FALSE, pit = TRUE)]
> # By the way, there are warnings although it works well (I ask on R-Help)
> 
> which.minima <- function(x) {
> 	if (!require(pastecs)) stop("pastecs library is required!")
> 	x <- as.vector(x)
> 	(1:length(x))[extract(turnpoints(x), no.tp = FALSE, peak = FALSE, pit = 
> TRUE)]
> }
> 
> which.minima(x)
> 
> Of course, you could optimize this code. This is just a rough solution!
> Best,
> 
> Philippe Grosjean


Philippe,

Thanks for the clarification. As with Andy's reply, it seems that my
closing thoughts were correct.

I was confused since the actual result of which.max() in Fred's post did
not match the data provided.

Best regards,

Marc




More information about the R-help mailing list