[R] Density estimate with bounds

Duncan Murdoch murdoch at stats.uwo.ca
Thu Nov 5 12:36:28 CET 2009


On 05/11/2009 4:35 AM, Justine Rochon wrote:
> Dear R users,
> 
> I would like to show the estimated density of a (0, 1) uniformly distributed
> random variable. The density curve, however, goes beyond 0 and 1 because of the
> kernel smoothing. 
> 
> Example:
> 
> x = runif(10000)
> plot(density(x))
> 
> Is there a way to estimate the density curve strictly within (0, 1) and still
> use some sort of smoothing?
> 
> Any help would be greatly appreciated.

One way is to extend the data by reflection on each end.  That is,

x <- runif(10000)
ex_x <- c(-x, x, 2-x)
den <- density(ex_x)
plot(den$x, 3*den$y, xlim=c(0,1), type="l")

You need the rescaling to 3*den$y because you've tripled the range.

Duncan Murdoch



More information about the R-help mailing list