R gives error with the mean but not with median

Good morning,
I am new and not a native-speaker, so sorry for errors. I have used this command to calculate the mean
mean(reporttb$no2,na.rm=TRUE)
but I got this error
The variable is not numeric nor logical
The weird thing is when i try to calculate the median instead, it gives me back a number without any problem. How is it possible?

Welcome to RStudio Community.

For us to diagnose your problem, we'll need a reproducible example. Please read this article for how to make one:

FAQ: What's a reproducible example (reprex) and how do I create one?

A quick way of doing this is to provide us the output of dput(reporttb) or, if its very long, dput(head(reporttb, 100)).

median() is defined for some types other than numeric. For example,

> median(c("a","c","b"))
[1] "b"
1 Like

@startz answer you should mark as the solution. To see more detail use help() for the two functions.

For help(mean) the argument, x

x An R object. Currently there are methods for numeric/logical vectors and date, date-time and time interval objects. Complex vectors are allowed for trim = 0, only.

That tells you that only dates and numbers can be used.

For help(median) the argument x

x an object for which a method has been defined, or a numeric vector containing the values whose median is to be computed.

is a little trickier. You can use numbers, it clearly says, but what is "an object for which a method has been defined?"

That's a bit of R geekery, which means that the default can be modified by a "method." But the interesting part is in Details

the default method will work for most classes (e.g., "Date") for which a median is a reasonable concept.

Why are characters a reasonable concept? Because they are ordered. a is less than c and c is less than a. For example:

 > letters[c(1,3,2)]
   #[1] "a" "c" "b"

the number being used is an integer index.

Note, however, that this works only for an odd number of arguments.

> median("a","c","b","d")
Error in if (na.rm) x <- x[!is.na(x)] else if (any(is.na(x))) return(x[FALSE][NA]) : argument is not interpretable as logical

because you can't have half an index.