[R] density() integrates to 1?

Adaikalavan RAMASAMY ramasamya at gis.a-star.edu.sg
Thu Sep 25 13:01:28 CEST 2003


We can try a to approximate the area under the curve using Trapezoidal rule on the plotting coordinates that density() produces. 


nbin <- 1024                   # number of bin

d <- density( rnorm(50000), n=nbin)

totalArea <- 0
 
for(i in 1:(nbin-1) ){

  xxx <- d$x[i+1] - d$x[i]     # width of bin
  yyy <- (d$y[i+1] + d$y[i])/2 # average height of bin

  binArea <- xxx*yyy
  totalArea <- totalArea + binArea
}

print(totalArea)               

We can see that the total area under the curve is close to 1 and the approximation gets better as nbin is increased (but this is always an overestimate due to the concavity of the normal curve).




More information about the R-help mailing list