 Min/Max with na.rm = TRUE can return different class to input

Is anyone hit with the fact that Min/Max with na.rm = TRUE will return different class from the input if there are no non-NA values?

In particular scenario I use min with na.rm = TRUE with group_by/summarise on a column which is of type integer. I then found the result is numeric - not integer. because min is returning -Inf for groups with no non-NA values.

Is there a library which gets around this or do I need to put a wrapper function around min?

To be frank I programmed around this in the early days but just letting my integers become numeric - but it doesn't seem right.

Sorry - I could have been a lot clearer. min is returning -Inf for groups with ALL NA values.
And the class of -Inf is numeric

The example below is trivial of course - but the class change has been an issue when used in summarise

inputdata <- rep(as.integer(NA),5)
print(class(inputdata))
minvalue <- min(inputdata, na.rm = TRUE)
print(minvalue)
print(class(minvalue))

It cant be that the end result is both Inf and integer, so one or the other will have to go...
If you want the vector class containing a mix of integers and Inf values to be integer you could cast them to integer and the Inf's will go to NA, is that acceptable ? otherwise what integer value would be ?

I want a vector with integers and NAs to always be returned as class integer.
Even if a vector is all NA (of class integer)
My criticism of min/max is that they don't return the same class for a given class of input.

Here is my best shot as a workaround - to be used in the situation where I know I want to use na.rm = TRUE

minNA = function(x) {

returnval <- min(x, na.rm = TRUE)

if (is.finite(returnval)) {
returnval
} else {
returnval <- as(NA, class(x))
}

}

inputdata <- rep(as.integer(NA),5)
print(inputdata)
print(class(inputdata))
#minvalue <- minNA(inputdata, na.rm = TRUE)
minvalue <- minNA(inputdata)
print(minvalue)
print(class(minvalue))
1] NA NA NA NA NA
 "integer"
 NA
 "integer"
Warning message:
In min(x, na.rm = TRUE) : no non-missing arguments to min; returning Inf
1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.