0

I have a simple function which finds numbers divisible by 4 in the following vector: x4 <- (2 4 6 8 10 12 14). But the function returns the values, and I want it to return indexes.

myef2 <- function(x){
  li2 <- NULL
  for(i in x){
    if(i %% 4 == 0) li2 <- c(li2, i)
  }
  return(li2)
}

the result is [1] 4 8 12. How do I modify it to give me a vector of indexes instead? Thanks for any help!

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
eNTROPY
  • 11
  • 1
  • 5
  • 3
    myef2 <- function(x) which(x%% 4 == 0) – Aaron Hayman Sep 20 '18 at 11:57
  • While I would be surprised if this question isn't a duplicate, the link posted is specifically after the first instance of the condition being met rather than the all instances, as is desired for this question. It is not difficult to derive a solution to this problem from the selected answer to the linked question, but other answers could be misleading. – Aaron Hayman Sep 20 '18 at 12:20

1 Answers1

2

How about which(x%%4==0), if x is a vector of numbers.

user2974951
  • 9,535
  • 1
  • 17
  • 24