On 23-Sep-10 16:52:09, Duncan Murdoch wrote:
>   On 23/09/2010 11:42 AM, wangguojie2006 wrote:
>> b<-runif(1000,0,1)
>> f<-density(b)
> 
> f is a list of things, including x values where the density is
> computed, 
> and y values for the density there.  So you could do it by linear 
> interpolation using approx or approxfun.  For example
> 
>  > b <- runif(1000,0,1)
>  > flist <- density(b)
>  > f <- approxfun(flist$x, flist$y)
>  > f(0.2)
> [1] 0.9717893
>  > f(-1)
> [1] NA
> 
> If you don't like the NA for an out-of-range argument, then choose 
> something different from the default for the "rule" argument to
> approxfun.
> 
> Duncan Murdoch

Or, perhaps more transparently (and more explicitly modifiable):

  b<-runif(1000,0,1)
  f <- density(b, from=0, to=1, n=512)
  plot(f$x, f$y, type="l", col="blue",
       xlim=c(0,1), ylim=c(0,1.5))     ## Plot the density estimate
  x0 <- 0.5                            ## Target value of x
  i0 <- max(which(f$x <= x0))
  i1 <- min(which(f$x > x0))
  u0 <- f$x[i0] ; v0 <- f$y[i1]
  u1 <- f$x[i1] ; v1 <- f$y[i1]
  y0 <- v0 + (v1-v0)*(x0-u0)/(u1-u0)   ## Linear interpolation
  points(x0, y0, pch="+", col="red")   ## Add interpolated point

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.hard...@manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 23-Sep-10                                       Time: 18:05:41
------------------------------ XFMail ------------------------------

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to