How to Fix: no non-missing arguments to min; returning Inf


One warning message you may encounter in R is:

Warning message:
In min(data) : no non-missing arguments to min; returning Inf 

This warning message appears whenever you attempt to find the minimum or maximum value of a vector that has a length of zero.

It’s important to note that this is only a warning message and it won’t actually prevent your code from running.

However, you can use one of the following methods to avoid this warning message entirely:

Method 1: Suppress the Warning Message

suppressWarnings(min(data))

Method 2: Define a Custom Function to Calculate the Min or Max

#define custom function to calculate min
custom_min <- function(x) {if (length(x)>0) min(x) else Inf}

#use custom function to calculate min of data
custom_min(data)

The following examples show how to use each method in practice.

Method 1: Suppress the Warning Message

Suppose we attempt to use the min() function to find the minimum value of a vector with a length of zero:

#define vector with no values
data <- numeric(0)

#attempt to find min value of vector
min(data)

[1] Inf
Warning message:
In min(data) : no non-missing arguments to min; returning Inf

Notice that we receive a warning message that tells us we attempted to find the minimum value of a vector with no non-missing arguments.

To avoid this warning message, we can use the suppressWarnings() function:

#define vector with no values
data <- numeric(0)

#find minimum value of vector
suppressWarnings(min(data))

[1] Inf

The minimum value is still calculated to be “Inf” but we receive no warning message this time.

Method 2: Define a Custom Function

Another way to avoid the warning message is to define a custom function that only calculates the minimum value if the length of a vector is greater than zero, otherwise a value of “Inf” is returned:

#define vector with no values
data <- numeric(0)

#define custom function to calculate min
custom_min <- function(x) {if (length(x)>0) min(x) else Inf}

#use custom function to calculate min
custom_min(data)

[1] Inf

Notice that the minimum value is calculated to be “Inf” and we receive no warning message.

Additional Resources

The following tutorials explain how to troubleshoot other common errors in R:

How to Fix in R: dim(X) must have a positive length
How to Fix in R: names do not match previous names
How to Fix in R: longer object length is not a multiple of shorter object length
How to Fix in R: contrasts can be applied only to factors with 2 or more levels

Leave a Reply

Your email address will not be published. Required fields are marked *