Home » How to Catch integer(0) in R (With Examples)

How to Catch integer(0) in R (With Examples)

by Erma Khan

Sometimes when you use the which() function in R, you may end up with integer(0) as a result, which indicates that none of the elements in a vector evaluated to TRUE.

For example, suppose we use the following code to check which elements in a vector are equal to the value 10:

#define vector of values
data #find elements in vector equal to 10
x 10)

#view results
x

integer(0)

Since none of the elements in the vector are equal to 10, the result is an integer of length 0, written as integer(0) in R.

It’s important to note that an integer(0) is not an error, but sometimes you may just want to be aware of when it occurs.

The following examples show how to catch an integer(0) in R.

Example 1: Catch integer(0) in R Using identical() Function

The easiest way to catch an integer(0) in R is to use the identical() function in the following manner:

#define vector of values
data #find elements in vector equal to 10
x 10)

#test if x is identical to integer(0)
identical(x, integer(0))

[1] TRUE

Since our result is equal to integer(0), R returns TRUE.

This lets us know that the result of the which() function is an integer of length 0.

Example 2: Catch integer(0) in R Using if else Function

Another way to catch an integer(0) is to define an if else function that returns something specific if an integer(0) occurs.

For example, we could define the following function to return the phrase “It is an integer(0)” if an integer(0) occurs:

#define function to catch integer(0)
integer0_test function(data) {
 
  if(identical(data, integer(0))) {
    return('It is an integer(0)')
  }

  else {
    return(data)
  }

}

We can then use this function:

#define vector of values
data #find elements in vector equal to 10
x 10)

#use function to test if x is integer(0)
integer0_test(x)

[1] "It is an integer(0)"

Since x is indeed an integer(0), our function returns the phrase that we specified.

And if x is not an integer(0), our function will simply return the result of the which() function:

#define vector of values
data #find elements in vector equal to 4
x 4)

#use function to test if x is integer(0)
integer0_test(x)

[1] 3 4

Our function returns 3 and 4 because these are the positions of the elements in the vector that are equal to the value 4.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Write Your First tryCatch() Function in R
How to Create a Nested For Loop in R
How to Return Value from Function in R

Related Posts