[R] question on mean, sum
Jim Lemon
drjimlemon at gmail.com
Mon Nov 14 09:26:34 CET 2016
Hi mokuram,
As others have noted, you will profit from a bit more knowledge about
"extraction":
sum(mtcars)
[1] 13942.2
This works because you have "extracted" the first column of the
"mtcars" data frame _as a data frame_
mtcars[1]
mpg
Mazda RX4 21.0
Mazda RX4 Wag 21.0
...
Volvo 142E 21.4
is.data.frame(mtcars[1])
[1] TRUE
mean(mtcars)
[1] NA
Warning message:
In mean.default(mtcars) :
argument is not numeric or logical: returning NA
Here you are trying to take the mean of the entire data frame. While
the mean function will "coerce" a single column to a vector, it won't
do so for an entire data frame. However, if you coerce the data frame
to a matrix:
mean(as.matrix(mtcars))
[1] 39.60853
That's the good news. The bad news is that the result is meaningless.
The same thing goes for:
sd(as.matrix(mtcars))
[1] 84.20792
It is almost always a good idea to read the error messages carefully
and try to understand them.
Jim
On Mon, Nov 14, 2016 at 2:01 PM, <mokuram at sina.com> wrote:
> Hi,
> I am working on functions such as sum(), mean() ...
>> sum(mtcars)[1] 13942.2> mean(mtcars)[1] NAWarning message:In mean.default(mtcars) : NA> sd(mtcars)Error in is.data.frame(x) : ()'double'
> why got different reply?Is this a BUG for the current version of R?my version info:version.string R version 3.3.1 (2016-06-21)
>
> Thank you very much for the help.
> mokuram
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list