Fixing R Errors: argument is not numeric or logical: returning na

This is actually a warning message and not an error message, but it would still be annoying if it comes up while you are writing an important program. The “Argument is not numeric or logical: returning na” message provides a fairly easy to understand description of the problem. It occurs while you are using the mean() function and it is an issue with the data type you are using.

The circumstances of this problem.

This problem occurs when using the mean() function. This function takes the mean value, which is a type of average, of the values in a vector used in the function.

> a = c(1,2,3,4,5)
> b = c(TRUE,FALSE,TRUE,TRUE,FALSE)
> c = c(“a”,”b”,”c”,”d”,”e”)
> mean(c)
[1] NA
Warning message:
In mean.default(c) : argument is not numeric or logical: returning NA

This example produces a warning message because the vector “c” contains characters and not numeric or logical values. This is why this message is simple to understand. It specifically indicates that the argument needs to be either a numeric or logical value.

What is causing this problem?

This problem results from entering neither a numeric nor logical argument into the mean() function. In the example above, it is a vector of characters however it can happen anytime a vector contains a value that is neither numeric or logical.

> a = c(1,2,3,4,5)
> b = c(TRUE,FALSE,TRUE,TRUE,FALSE)
> c = c(“a”,”b”,”c”,”d”,”e”)
> mean(a)
[1] 3

In this example, the vector “a” contains numeric values. The mean value here is 3 because the values in “a” are 1-5. Because these values are numeric, there is no message.

> a = c(1,2,3,4,5)
> b = c(TRUE,FALSE,TRUE,TRUE,FALSE)
> c = c(“a”,”b”,”c”,”d”,”e”)
> mean(b)
[1] 0.6

Here “b” which contains logical values of “TRUE” and “FALSE” resulting in an acceptable argument. You get a mean of 0.6, this is because the mean() function sees “TRUE” and “FALSE” as numeric values of 1 and 0 respectively.

How to fix this error.

If you have complete control over the data, one solution is to make sure that the vector you are using in the mean() function contains only numeric or logical values. In such cases, this may mean manually removing bad values.

Otherwise, you will want to use some form a filter to find and eliminate any unwanted values. The point, in either case, is to eliminate any values that you do not want to apply to the mean() function. The key to this problem is to ensure that you are only using numeric or logical values in the mean() function.