Try to search your question here, if you can't find : Ask Any Question Now ?

# Finding first,second and third local minima indexes in array data

HomeCategory: stackoverflowFinding first,second and third local minima indexes in array data

Given an array with integers, I want to find the first,second and third local minima index numbers (x,y) in the array according to some criteria that I define.

The main idea is ;
finding the lowest z values with the highest x and the lowest y index number;

To achieve that I define three cases as shown in below,

1. Find the first local minima of z for x,y index. (white
dashed line in the plot; this will be x=14,y=10)

2. Find the second local minimum z value with the highest index of x (possible) but with the lowest index for y (this will be x=20,y=10)

3. Find the third local minimum z value with the highest index of x (possible) but with the second lowest index of y (this will be x=20,y=12)

finally I want to output of index numbers of list items 1,2 and 3 at above with the lowest z value.

So the first local minima to choose; x=20,y=12
So the second local minima to choose; x=20,y=10
So the second local minima to choose; x=14,y=10

I tried something like this

``````set.seed(444555)

df <- data.frame(
x = c(seq(2,20,2)),
y = c(rep(c(seq(2,20,2)),each=10)),
z = round(c(runif(40,90,100),
replicate(6,c(runif(4,90,100),runif(6,0,10)))),0))
``````

for plot

``````library(ggplot2)
ggplot(df, aes(x, y)) +
geom_tile(aes(fill = z), colour = "grey50", width = 2, height = 2)+
geom_vline(aes(xintercept=14),linetype="dashed",colour="white",size=1)+
geom_hline(aes(yintercept=10),linetype="dashed",colour="white",size=1)+
scale_x_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
scale_y_continuous(expand = c(0, 0),breaks=seq(0,50,1))+
geom_text(aes(label=z),hjust=0.5, vjust=0.5, color="black", size=4)+

theme(legend.position = "none")
``````

The function

``````minima_finder <- function(x,y,z){

first_finima_x=x[which.min(z)&z<=10][1]
first_finima_y=y[which.min(z)&z<=10][1]

second_finima_x=x[which.min(z)&z<=10][2]
second_finima_y=y[which.min(z)&z<=10][2]

data.frame(first_min_x,first_min_y,second_min_x,second_min_y)

}

dff <- df%>%
group_by(y)%>%
do(data.frame(., minima_finder(.\$x,.\$y,.\$z)))
``````

I can only find the 1 case (first local min indexes correctly) Case 2 and case 3 how can I do that?

thx