E.hu
E.hu

Reputation: 7

indice of vector element in loop - R

i have a numbers vector and i need to find the index of the first number that is greater than 24 and divisible by 13, if no number answers the conditions print 0. this is the code i wrote:

numbers_vector=c(1,5,26,7,94)
for(i in numbers_vector){
  if(i>24&&i%%13==0){
    print(i)
  }else{
    print(0)
  }
}

the answer it returns:

[1] 0
[1] 0
[1] 26
[1] 0
[1] 0

it should return the number 3 (the index), as 26 answers the conditions.

Can anyone see what im doing wrong? Thanks

Upvotes: 0

Views: 44

Answers (2)

iod
iod

Reputation: 7592

which.max(numbers_vector>24 & numbers_vector%%13==0)

This will give you the result you're looking for, but if none of the numbers fits, it returns NA. If you want zero in such cases, do this :

a=which.max(numbers_vector>24 & numbers_vector%%13==0)
ifelse(is.na(a), 0, a)

Two general comments: a. avoid automatically going for the for loop. R's greatest strength is in vectorized calculations. B. Avoid using print to return your result.

Upvotes: 1

Omry Atia
Omry Atia

Reputation: 2443

Only a small change is needed:

numbers_vector=c(1,5,26,7,94)
for(i in numbers_vector){
  if(i>24 && i%%13==0){
    print(which(numbers_vector == i))
  }else{
    print(0)
  }

}

You are printing i, which is the number itself rather than its index

Upvotes: 0

Related Questions