Search code examples
indexingduplicatesmaxintervals

Index maximum of duplicate maximum values in R


I know which.max is able to tell me the index of the first occurrence of the maximum value, however I want to obtain the maximum index value of all indexes duplicate maximum values in a given range.

Below is the data I am working with:

#Given Data Set
Dataset1 <- data.frame(Index=1:6, Value=c(.456,.92,.88,.92,.88,0.85))
Dataset1

# Index Value
1     1 0.456
2     2 0.920
3     3 0.880
4     4 0.920
5     5 0.880
6     6 0.850

#--------------------------

#Create Filtered Combinations
N=nrow(Dataset1)

Comb<-data.frame(t(combn(seq(1:(N)), 2)))
library("plyr")
library("dplyr")
FComb<-Comb %>%
  filter(X2-X1>1) %>%
  select(X1,X2)

FComb.mat<-as.matrix(FComb) #Filtered Combination set as matrix
colnames(FComb.mat)[1:2] <- c("ind1","ind2")

#--------------------------

#Finding maximum value from original dataset in the range between "ind1" & "ind2"
fun <- function(x,y) max(Dataset1$Value[(.x <- x:y)[-c(1, length(.x))]])
Max.Val = as.matrix(mapply(fun, FComb.mat[,1], FComb.mat[,2]))

PROBLEM:

I would like to obtain the last column "IndexMax" as shown below.

For example for ind1=1 & ind2=5 (i.e row #3), the max flow value from Dataset1 between Index=1:5 is 0.920. The index of this maximum value can be either 2 or 4, but I would like to choose 4 as it is the maximum value of the indexes.How would I implement this?

Final
#   ind1 ind2 Max.Val IndexMax
1     1    3    0.92        2
2     1    4    0.92        2
3     1    5    0.92        4
4     1    6    0.92        4
5     2    4    0.88        3
6     2    5    0.92        4
7     2    6    0.92        4
8     3    5    0.92        4
9     3    6    0.92        4
10    4    6    0.88        5

Solution

  • I actually figured it out myself. In case this is of use to anyone else in the future:

    fun2 <- function(x,y) max((which(Dataset1[,2][(.x <- x:y)][-c(1,length(.x))]==max(Dataset1[,2][(.x <- x:y)][-c(1, length(.x))])))+x)  
    Max.Pos=as.matrix(mapply(fun2, FComb.mat[,1],FComb.mat[,2]))
    
    Final<-data.frame(FComb.mat,Max.Val,Max.Pos)