简体   繁体   中英

Obtain count data from R density plot

Is there a method to transform the densities returned by the density() function into counts? I've tried doing things like:

dens = density(x)
plot(dens$x,dens$y*dens$n*(dens$x[2]-dens$x[1]))

However, I'm not sure this math is correct since I don't know entirely what goes on under the density function.

A count is going to sum to the number of input points, so just rescale the dens$y to be equal to the length of your input vector:

> x=rnorm(1000,5)
> 
> dens=density(x)
> plot(dens$x,dens$n*dens$y/sum(dens$y))

I think your method of multiplying by binwidth is equivalent to mine of dividing by the sum. And probably quicker, but does rely on a regular bin size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM