[R] Generate data - function
Petr Savicky
savicky at cs.cas.cz
Wed Feb 1 09:43:24 CET 2012
On Tue, Jan 31, 2012 at 01:59:13PM -0500, Val wrote:
> Hi petr,
>
> >Can the required density be understood as a piecewise
> >linear function going through 4 or 5 given points?
>
> That is my problem. The function should be nonlinear. However, we can break
> it down to the first 3 or 4 points could be linear and then nonlinear
> function. On the later points can we apply sort of spline function or local
> polynomials?
Hi.
Generating numbers from a distribution, whose inverse distribution
function is given by a spline, can be done as follows.
library(splines)
#prepare a spline for the inverse distribution function
eps <- 0.27
xorig <- c(0, 0.1, 0.4, 0.6, 0.9, 1)
yorig <- cumsum(c(0, 1, 1 + eps, 1 - 2*eps, 1 + eps, 1))
ispl <- interpSpline(xorig, yorig)
#generate random sample
z <- predict(ispl, runif(100))$y
#plot the distribution function and original points
invDist <- predict(ispl, seq(0, 1, length=501))
plot(invDist$y, invDist$x, type="l")
points(yorig, xorig, col=2)
#plot the density function
invDeriv <- predict(ispl, seq(0, 1, length=501), deriv=1)
xDensity <- invDist$y
yDensity <- 1/invDeriv$y
plot(xDensity, yDensity, type="l")
The density function in the above example is bimodal, but
in order to make it close to your graphs, the original
points xorig, yorig should be changed.
Note that the letters x, y correspond to the usual notation
for the spline. Since the spline expresses the inverse
distribution function, x and y are exchanged for the plots.
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list