User error (was [R] density() returns a density function that does not add up to 1)

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Fri Aug 30 22:28:46 CEST 2002


On Fri, 30 Aug 2002, Jonathan Li wrote:

> I ran into this curious problem:

(or, I did something silly)

> > d <- rnorm(100)
> > d.density <- density(d)
> > sum( d.density$x * d.density$y)
> [1] 2.517502
>
> Admittedly the method of computing the mass under the density curve at
> line 3 is crude.

(and got a nonsensical answer)

> But 2.5 is pretty far from 1, the value it should be.
>
> I tried a few other dataset and got similar result. Am I missing
> something obvious?
> Or is the return of density() not supposed to be normalized?

I think you intended

sum( unique(diff(d.density$x)) * d.density$y )

Your sum is 512x the estimate of E(X).

-- 
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 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list