0

I have a data frame with two columns:

dd <- read.table(text = "
344 0 
350 16 
366  11 
376   8 
380  28 
397  55
398  45  
400  19 
402  30
408  20
415   0
")

I want to subset the data between the two minimum local around the highest value in the second column (55).

The result will be:

376   8 
380  28 
397  55
398  45  
400  19

It must contain a minimum local function because the dimension of sub-data frame is variable

dd <- read.table(text = "
460  0 
461  2 
463  16 
469  33 
471 13 
473 23 
479 38 
480 168 
481  0")

1 Answers1

2

Subsetting to N surrounding values should be as easy as that:

p.max <- which.max(dd$V2)
range <- -2:2
dd[p.max + range, ]

#   V1 V2
# 4 376  8
# 5 380 28
# 6 397 55
# 7 398 45
# 8 400 19

To subset between the local minimums around the global maximum you can do something like this:

dd <- read.table(text = "344 0 
350 16 
366  11 
376   8 
380  28 
397  55
396  50
398  45  
400  19 
402  30
408  20
415   0")

library(data.table)
minimums <- function(x) which(x - shift(x, 1) < 0  & x - shift(x, 1, type='lead') < 0)
p.max <- which.max(dd$V2)
local.mins <- minimums(dd$V2)
local.mins <- c(last(local.mins[local.mins < p.max]), first(local.mins[local.mins > p.max]))
dd[local.mins[1]:local.mins[2], ]

Here I have used data.table because it has some useful functions like shift and first.

minimums function was taken from answer to this question: Finding local maxima and minima in R

This code does not seem to work for cases where local minimum does not exist, e.g. min value is last or first.

Bulat
  • 6,869
  • 1
  • 29
  • 52