How to check whether a value is present in a vector with a UDF and for loop

Viewed 30

The goal is to create a function that will test to see if a number is in a vector.

For example, you would call it like this: function_name(3,c(1,2,3)) and it would return TRUE since 3 is one of the elements in the function.

My function works when the number is in the vector and it will output TRUE, but when the number is not in the vector, it will give the error, "missing value where TRUE/FALSE needed".

numCheck <- function(a,b){
  for (num in b){
    if (a == b[num]){
      return(T)
      break
    }
    else{
      num <- num + 1
    }
    if (num > length(b)){
      return(F)
      break
   }
  }
}
print(numCheck(3,c(1,2,4)))
1 Answers

Although we can use %in% as a built-in function for what you're intending to do, here's how your function can be changed to work properly; we can assume that the output is FALSE and if the value was present in the vector, then our function will change the output to TRUE will break the loop and prints the returns output.

numCheck <- function(a, b){
out <- FALSE
  for (num in b){
      if (a == num) {
          out <- TRUE 
          break}
  }
  
  return(out)
  
  }


numCheck(2, c(1,5,3))
#> [1] FALSE
numCheck(0, c(0,1,5))
#> [1] TRUE

When you are using val in vector as your iterator, you don't go to the next step by adding to the value. Read more here: https://www.tutorialkart.com/r-tutorial/r-iterate-over-items-of-vector/

You are mixing and matching while and for loops together. Here's another tutorial for while loops: https://www.datamentor.io/r-programming/while-loop/

Related