Jorge Mendes
Jorge Mendes

Reputation: 97

R-get the position of max value in a vector from a matrix

pond_matriz<-matrix(c(0,17.6,18.3,9.1,6.1,12.3,4.5,9.4,
           + 0,0,173.4,10.6,5.4,20.3,4.0,9.9,
           + 0,149.4,0,10.9,5.3,22.5,3.7,10.2,
           + 0,6.9,8.3,0,6.2,14.5,3.9,17.8,
           + 0,4.2,4.7,7.3,0,5.3,14.4,13.4,
           + 0,14.9,19.3,16.3,5.3,0,3.4,11.5,
           + 0,4.4,4.8,6.5,21.7,5.3,0,10.8,
           + 0,3.2,3.8,9.0,5.7,5.1,3.1,0),nrow=8, byrow=T)

pond0<-pond_matriz[1,]
pond1<-pond_matriz[2,]
pond2<-pond_matriz[3,]
pond3<-pond_matriz[4,]
pond4<-pond_matriz[5,]
pond5<-pond_matriz[6,]
pond6<-pond_matriz[7,]
pond7<-pond_matriz[8,]

f1<- function(line,cost,k){   #cost is not used yet

if(k!=0){
 # is.integer(k)
  new_line<-line[-c(k)]
  pos<-(which.is.max(pond1)-1)
  cat("go to position",pos,"\n")

 }
  if(k==0){
    pos<-(which.is.max(line)-1)
    cat("go to position",pos,"\n")
  }

}

When I want to go from position 0 (pond0), I do;

  >  g<-c(0) # I dont want to go from 0 to 0
  >  f1(pond0,0,g)
  go to position 2  #18.3

> pond0
[1]  0.0 17.6 **18.3**  9.1  6.1 12.3  4.5  9.4

Here its nice, then I do;

>  g<-c(0)    #Dont want to return yet to position 0
>  f1(pond2,0,g)
go to position 1 #149.4

> pond2
[1]   0.0 **149.4**   0.0  10.9   5.3  22.5   3.7  10.2

here, its good too, then;

> g<-c(3) #pos2
> f1(pond1,0,g)
go to position 4 

> pond1
[1]   0.0   0.0 *173.4*  10.6   5.4  **20.3**   4.0   9.9

Here is my problem, I know that I said to remove 173.4, but i just want that pos2 is not considered because I already passed there, and i want to know how can i do to said "go to position 5". how can I consider that 20.3(cause 173.4 is pos2 and i've been there already) is the maximum without changing his position

Upvotes: 0

Views: 492

Answers (1)

storm surge
storm surge

Reputation: 841

Surely there is a better way to do this but this one worked with your code:

f1<- function(line,cost,k){   #cost is not used yet

  if(k!=0){
    # is.integer(k)

    new_line<-c(rep(NA,k),line[(k+1):length(line)])


    pos<-(which.max(new_line)-1)
    cat("go to position",pos,"\n")
}
  if(k==0){
    pos<-(which.max(line)-1)
    cat("go to position",pos,"\n")

  }

}

new_line is now a vector with NA value for the positions you want to skip without losing the position of the remaining values

the results for your examples are as follow:

> g<-c(0)
> f1(pond0,0,g)
go to position 2 
> pond0
[1]  0.0 17.6 **18.3**  9.1  6.1 12.3  4.5  9.4
>     
> g<-c(0)
> f1(pond2,0,g)
go to position 1 
> pond2
[1]   0.0 **149.4**   0.0  10.9   5.3  22.5   3.7  10.2
>     
> g<-c(3)
> f1(pond1,0,g)
go to position 5 
> pond1
[1]   0.0   0.0 173.4  10.6   5.4  **20.3**   4.0   9.9

I have switched to the which.max function from the base package because I haven't got the one you use.

Hope it helps you!

Upvotes: 1

Related Questions