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
CodePudding user response:
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))
CodePudding user response:
If you use print
, each iteration will print something to the console. I think we never need print
in serious R
loops, and seldom need for
loops in serious R. Regardless, here are two separate ideas of a solution, (where I think you're mixing up the two).
1. Max. is known
In this case we just compare each element with max_value
and if
they match, store the i
ndex in the res
ult.
n <- length(vect_1)
res <- NA
for (i in seq_len(n)) {
if (vect_1[i] == max_value) {
res <- i
}
}
res
# [1] 6
2. Max. is unknown
In this case, we don't know the max yet. We want a starting value mx
that is smaller than everything that may come, which is -Inf
. if
we get something greater, we update mx
and store the index in the res
ult.
n <- length(vect_1)
mx <- -Inf
res <- NA
for (i in seq_len(n)) {
if (vect_1[i] > mx) {
mx <- vect_1[i]
res <- i
}
}
mx
# [1] 10
res
# [1] 6
Concluding remark
Note, that I consider this might be a nice task for practicing for
loops and train respective thinking. However there's no point to use the R
language for that, where we simply may do
which.max(vect_1)
# [1] 6
which gives the same result (if there are no ties).