# [R] Random number from density()

Mark Fisher mark at markfisher.net
Mon Apr 2 18:56:08 CEST 2007

```Arianne ALBERT wrote:
> Hello,
>
> I'm writing some genetic simulations in R where I would like to place
> genes along a chromosome proportional to the density of markers in a
> given region. For example, a chromosome can be presented as a list of
> marker locations:
>
> Chr1<-c(0, 6.5, 17.5, 26.2, 30.5, 36.4, 44.8, 45.7, 47.8, 48.7, 49.2,
> 50.9, 52.9, 54.5, 56.5, 58.9, 61.2, 64.1)
>
> Where the numbers refer to the locations of markers along the
> chromosome. As you can see, there are a lot of markers around 50, but
> they are less dense elsewhere. I would like to take this information to
> randomly select a location on the chromosome to put a gene, where we are
> more likely to pick a location with high marker density (instead of
> using a uniform distribution between 0 and 64.1).
>
> So far I've used density(Chr1) to generate the probability density, but
> can this also be used to generate a random number? All the help I can
> find suggests getting the quantile function (the reciprocal of the
> integral of the pdf), however, it doesn't seem as though density()
> returns a pdf that can be manipulated in this way. Any suggestions?
>
>
> Arianne
>

I'm new to R and maybe I don't understand what you want, but here's a
suggestion:

Chr1 <- c(0, 6.5, 17.5, 26.2, 30.5, 36.4, 44.8, 45.7, 47.8, 48.7, 49.2,
50.9, 52.9, 54.5, 56.5, 58.9, 61.2, 64.1)
n <- length(Chr1)-1
fun <- approxfun(0:n/n, Chr1)
ran <- fun(runif(10000))
hist(ran)

--Mark.

```