Home » How to Fix in R: argument is not numeric or logical: returning na

How to Fix in R: argument is not numeric or logical: returning na

by Erma Khan

One warning you may encounter in R is:

Warning message:
In mean.default(df) : argument is not numeric or logical: returning NA

This warning occurs when you attempt to calculate the mean of some object in R that is not numerical or logical.

This tutorial shares exactly how to handle this warning in practice.

How to Reproduce the Warning

Suppose we create the following data frame in R:

#create data frame
df frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

If we attempt to calculate the mean of a character column or if we attempt to calculate the mean of the entire data frame, we’ll receive a warning:

#attempt to calculate mean of character column
mean(df$team)

Warning message:
In mean.default(df$team) : argument is not numeric or logical: returning NA

#attempt to calculate mean of entire data frame
mean(df)

Warning message:
In mean.default(df) : argument is not numeric or logical: returning NA

The mean() function only takes a numeric vector as an argument, which explains why we receive a warning in both scenarios.

How to Handle the Warning

The way to handle this warning is to only use the mean() function with numeric vectors.

For example, we could calculate the mean of the points column since it’s numeric:

#calculate mean of points column
mean(df$points)

[1] 91.6

Or we could use the sapply() function to calculate the mean of every column in the data frame:

#calculate mean of every column in data frame
sapply(df, mean, 2)

    team   points  assists rebounds 
      NA       90       33       28 

Warning message:
In mean.default(X[[i]], ...) :
  argument is not numeric or logical: returning NA

We’re able to calculate the mean of each numeric column, but still receive a warning message since we attempted to calculate the mean of the ‘team’ character column.

To avoid this warning entirely, we could use the sapply() function with just the three numeric columns:

#calculate mean of each numeric column
sapply(df[c('points', 'assists', 'rebounds')], mean, 2)
  points  assists rebounds 
      90       33       28

Notice that the mean of each numeric column is successfully shown and we receive no warning message.

Additional Resources

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

How to Fix: the condition has length > 1 and only the first element will be used
How to Fix: non-numeric argument to binary operator
How to Fix: dim(X) must have a positive length
How to Fix: error in select unused arguments

Related Posts