0

I'm trying to write a condition that says if "i" doesn't exist in the vector print 0 - meaning in this vector it should print just [3]

number_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) 
    }
Tobias Wilfert
  • 919
  • 3
  • 14
  • 26
  • 2
    You don't need a loop `as.integer((number_vector > 24) & (number_vector %%13 == 0))` – akrun Dec 19 '18 at 07:13
  • Welcome to Stack Overflow! Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer! See also: [How To Ask](https://stackoverflow.com/questions/how-to-ask]) – stasiaks Dec 19 '18 at 07:16
  • Possible duplicate of [Check if element exists in vector R](https://stackoverflow.com/questions/40527925/check-if-element-exists-in-vector-r) – stasiaks Dec 19 '18 at 07:18
  • `v <- c(1,5,26,7,94); which((v >24) & (v%%13 == 0))` – jogo Dec 19 '18 at 07:23
  • I was asked to do a loop, because in another vector for same code 'i' is not exist and the answer should say just [0]. my problem is that I get answer for each element in the vector instead of just [0]. [1] 0 [1] 3 [1] 0 [1] 0 – yuval dulitzky Dec 19 '18 at 08:12
  • `v <- c(1,5,27,7,94); w <- which((v >24) & (v%%13 == 0)); if (length(w)==0) 0 else w` – jogo Dec 19 '18 at 08:47

1 Answers1

1

Here is the solution for your hometask (using a loop):

v <- c(1, 5, 26, 7, 94)
w <- 0
for (i in 1:length(v)) {
  if ((v[i] >24) & (v[i] %% 13 == 0)) { w <- i; break }
}
w

Without the restriction the code can be short:

v <- c(1,5,27,7,94)
w <- which((v >24) & (v%%13 == 0))
if (length(w)==0) w <- 0
jogo
  • 12,469
  • 11
  • 37
  • 42