[R] Question about density()

Gabor Grothendieck ggrothendieck at myway.com
Fri Mar 4 03:11:46 CET 2005


Dan Bolser <dmb <at> mrc-dunn.cam.ac.uk> writes:

: 
: If I integrate over the result of the density() funcion, is the result 1?
: 
: For example 
: 
: x <- rnorm(1000)
: plot(density(x))
: 
: Does the area under the curve I see sum to 1?
: 
: What I really want to know is if I can directly compare two particular
: curves, generated like this
: 
: x <- rnorm(1000)
: plot(density(x))
: 
: a.seq <- seq(min(x),max(x),0.01)
: lines(a.seq,dnorm(x=a.seq,mean=mean(x),sd=sd(x)))
: 
: I guess they are directly comparable if the area under density sums to
: one.
: 
: Is this correct?

We can integrate it to find out:

R> set.seed(1)
R> z <- density(rnorm(10000))
R> f <- approxfun(z$x, z$y, yleft = 0, yright = 0)
R> integrate(f, -Inf, Inf)
1.000978 with absolute error < 6.6e-05




More information about the R-help mailing list