What is is.finite() Function in R

In the process of data cleaning, you often need to identify and remove non-finite values from the datasets before analysis. The actual non-finite (infinite) values are Inf(positive infinity) and –Inf(negative infinity). NA and NaN are special cases.

is.finite()

demo of is.finite() Function in R

R is.finite() function checks whether input objects are finite. By default, it handles atomic vectors, but it can be numeric vectors, matrices, and arrays. It returns a logical vector of the same length where TRUE suggests that the corresponding element is a finite number, and FALSE suggests that it is not.

The is.finite() method does not work directly with Data Frames because it is not a list of vectors of potentially different types. If you try to work with data frames, it will give you an error like this: “Error in is.finite(df) : default method not implemented for type ‘list'”.

Syntax

is.finite(obj)

Parameters

Name Value
obj It is an input R object that will be checked for finite values.

Return value

  1. If an element is a regular number, is.finite() returns TRUE.
  2. If an element is Inf or -Inf, it returns FALSE.
  3. If an element is NA (Not Available) or NaN (Not A Number), it returns FALSE.

Finite and Infinite Numbers

vec <- c(1, -1, Inf, 0, -Inf)

is.finite(vec)

# Output
# [1] TRUE TRUE FALSE TRUE FALSE

You can see that the output vector’s length is the same as the input vector’s length, and infinite numbers are replaced by FALSE. NaN represents an undefined numeric number.

Passing “NA”

Passing NA to is.finite() function

vec <- c(1, NA, -1, NA)

is.finite(vec)

# Output
# [1] TRUE FALSE TRUE FALSE

Extracting finite values from the vector

Using vector indexing, we can extract the finite values from the vector with the help of is.finite() function.

vec <- c(1, NA, -1, NA)

finite_vals <- vec[is.finite(vec)]

print(finite_vals)

# Output: [1] 1 -1

Matrices

We can also check for finite values in the matrix. It will return TRUE for a finite number in individual elements and FALSE otherwise.

mat <- matrix(c(1, NaN, 3, Inf, 5, 6), nrow = 2, ncol = 3)
print("Finite values in matrix:")
print(is.finite(mat))

# Output

# [1] "Finite values in matrix:"

#       [,1]  [,2]  [,3]
# [1,] TRUE  TRUE   TRUE
# [2,] FALSE FALSE  TRUE

You can see that the output matrix has the same size as the input matrix. Only its elements are boolean values.

Arrays

Let’s create a 3D array with a mix of finite, infinite, and NaN numbers.

# Defining an array
arr <- array(c(1, 2, 3, Inf, NaN, -Inf, 7, 8), dim = c(2, 2, 2))

print("Original Array:")
print(arr)

# Applying is.finite() function to the array
finite_arr <- is.finite(arr)
print(finite_arr)

Output

Output of is.finite() function with array

You can see that the output is a logical array of the same dimension as an input array. 

That’s all, mates!

Leave a Comment