Hi there, In the following example, sd() can be applied to a character vector. However, mean() can not be run in a similar way. Why? I have read sd() man page, however, I don't find information about that behavior. > x <- as.character(1:10) > sd(x) [1] 3.02765 > mean(x) [1] NA Warning message: In mean.default(x) : argument is not numeric or logical: returning NA Regards, Jinsong
R. Michael Weylandt
2012-Oct-27 09:48 UTC
[R] why sd() can be applied to character vector?
On Sat, Oct 27, 2012 at 10:16 AM, Jinsong Zhao <jszhao at yeah.net> wrote:> Hi there, > > In the following example, sd() can be applied to a character vector. > However, mean() can not be run in a similar way. Why? > > I have read sd() man page, however, I don't find information about that > behavior. > >> x <- as.character(1:10) >> sd(x) > [1] 3.02765 >> mean(x) > [1] NA > Warning message: > In mean.default(x) : argument is not numeric or logical: returning NAPractically, I see $R_HOME/src/library/stats/src/cov.c:633 has x = PROTECT(coerceVector(x, REALSXP)); which seems to be responsible for the behavior you note (eventually calling $R_HOME/src/main/util.c:1463), but mean.default catches the character case early and returns NA_real_. None of that explains the reasoning however and it does seem a little anomalous Cheers, Michael
On 27/10/2012 10:16, Jinsong Zhao wrote:> Hi there, > > In the following example, sd() can be applied to a character vector. > However, mean() can not be run in a similar way. Why? > > I have read sd() man page, however, I don't find information about that > behavior.Well, it is there: x: a numeric vector or an R object which is coercible to one by ?as.vector?. > as.vector(x, 'numeric') [1] 1 2 3 4 5 6 7 8 9 10 And it is different from mean() because that is generic and allows many other forms of input, whereas for sd() one knows what to coerce to.> > > x <- as.character(1:10) > > sd(x) > [1] 3.02765 > > mean(x) > [1] NA > Warning message: > In mean.default(x) : argument is not numeric or logical: returning NA > > Regards, > Jinsong > > ______________________________________________ > R-help at r-project.org mailing list > 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.-- Brian D. Ripley, ripley at stats.ox.ac.uk Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/ University of Oxford, Tel: +44 1865 272861 (self) 1 South Parks Road, +44 1865 272866 (PA) Oxford OX1 3TG, UK Fax: +44 1865 272595