Interpreting Errors in R: ‘max’ not meaningful for factors

Solution to 'max' not meaningful for factors error in R

At one point or another you may encounter the following error in R:

'max' not meaningful for factors

This simply indicates that you are attempting to take the ‘max’ of a variable that is of the class¬†factor.

For example, this error is thrown if we attempt to take the max of the following vector:

#create a vector of class vector
factor_vector <- as.factor(c(1, 7, 12, 14, 15))

#attempt to find max value in the vector
max(factor_vector)

#Error in Summary.factor(1:5, na.rm = FALSE) : 
#  'max' not meaningful for factors

By definition, the values in a factor vector are of nominal class, which means there is no meaningful ordering of the values. Thus, there is no ‘max’ value to be found.

One simple solution to find the max of a factor vector is to simply convert it into a character vector, and then into a numeric vector:

#convert factor vector to numeric vector and find the max value
new_vector <- as.numeric(as.character(factor_vector))
max(new_vector)

#[1] 15

If your factor vector simply contains the names of factors, then it is not possible to find the max value, even after converting the factor vector into a numeric vector, since it doesn’t make since to find the ‘max’ of a list of names.

#create factor vector with names of factors
factor_vector <- as.factor(c("first", "second", "third"))

#attempt to convert factor vector into numeric vector and find max value
new_vector <- as.numeric(as.character(factor_vector))
max(new_vector)

#Warning message:
#NAs introduced by coercion 
#[1] NA

It’s worth noting that R can find the max of numeric vectors, date vectors, and character vectors without running into any issues:

numeric_vector <- c(1, 2, 12, 14)
max(numeric_vector)

#[1] 14

character_vector <- c("a", "b", "f")
max(character_vector)

#[1] "f"

date_vector <- as.Date(c("2019-01-01", "2019-03-05", "2019-03-04"))
max(date_vector)

#[1] "2019-03-05"

Thus, if you are attempting to find the max value in a vector, simply make sure that your vector is not of the type factor.

Leave a Reply

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