rseriesminima

Find local minima of series


There is a series 8,7,6,5,6,7,8,7,6,7,8 which has local minima at 5 and 6.

How to get this using R?


Solution

  • library(zoo)
    
    x <- c(8,7,6,5,6,7,8,7,6,7,8)
    
    # eliminate runs
    r <- rle(x)
    r$lengths[] <- 1
    xx <- inverse.rle(r)        
    
    xx[ rollapply(c(Inf, xx, Inf), 3, function(x) x[2] < min(x[-2])) ]
    ## [1] 5 6
    

    If we knew that x had no runs, as is the case in the question's example, we could omit the three lines that eliminate runs and replace xx in the last statement with x. Use -Inf in place of both occurrences of Inf if you don't want to consider endpoints.

    It is assumed that the input c(2, 1, 1, 3) should result in output of 1 once.