Search code examples
rloopsmax

How to find the index without using which(), match(), %in%?


I am unable to find the index position of my max_value without using which(), match(), %in%

vect_1 <- c(2, 3, 1, 4, 5, 10, 7, 6, 9, 8)

n <- length(vect_1)
max_value <- vect_1[1]

for (i in 1:n) {
  if (vect_1[i] > max_value) {
    max_value <- vect_1[i]
  }
  if (max_value == vect_1[i]) {
    print(i)
  }
}

[1] 1
[1] 2
[1] 4
[1] 5
[1] 6

I know the max_value is 10 but I am unable to get i == 6 only


Solution

  • The loop should look like this:

    n <- length(vect_1)
    max_value <- vect_1[1]
    max_value_idx <- 1
    
    for (i in 1:n) {
      if (vect_1[i] > max_value) {
        max_value <- vect_1[i]
        max_value_idx <- i
      }
    }
    print(paste0("Max value: ", max_value," Index: ",max_value_idx))