[R] Inverse fuction of ecdf

Duncan Murdoch murdoch at stats.uwo.ca
Mon Jan 29 00:23:44 CET 2007


On 1/28/2007 5:41 PM, Geoffrey Zhu wrote:
> Hi Everyone,
> 
> I want to generate some random numbers according to some empirical
> distribution. Therefore I am looking for the inverse of an empirical
> cumulative distribution function. I haven't found any in R. Can anyone
> give a pointer?

sample() works fine if you have a sample to start from.  If you really 
need to start from an ecdf, you could generate x and prob args to 
sample() by looking inside the ecdf object.  For example:

x <- rbinom(100, 100, 0.2)
e <- ecdf(x)

Now either of these should give you what you want.

size <- 1000
sample(x, size, replace=TRUE)

or

vals <- get("x", environment(e))
probs <- diff(c(0, get("y", environment(e))))
sample(vals, size, replace=TRUE, prob=probs)

Duncan Murdoch



More information about the R-help mailing list