[R] Constraints when sampling from a distribution

Peter Ehlers ehlers at ucalgary.ca
Thu Dec 9 04:04:35 CET 2010


On 2010-12-08 17:07, Anup Nandialath wrote:
>   Dear R-helpers,
>
> My question is related to how to impose constraints when when sampling from a distribution.
>
> For example, suppose I'm sampling a vector from a multivariate normal distribution
>
> vbeta<- 100*diag(2)
> mbeta<- c(1,1)
> ans<- beta<- c(rmvnorm(1,mbeta,vbeta))
>
> ans will thus be a vector with two elements.
>
> My question is how do I place a restriction on one of the elements of the ans vector. For example, suppose my goal is to reject any draw for ans[2] below -1 and above 1, how should I implement that in the above setting?
>

What's wrong with just rejecting those cases after
they've been generated. Not efficient, but easy.

Say you want 10 random points. Generate 500 (or
whatever seems reasonable), toss out the ones
you don't want, randomly select 10 from the rest.

  library(mvtnorm)  ## (I assume)
  set.seed(31415)
  tmp <- rmvnorm(500,mbeta,vbeta)
  tmp1 <- tmp[which(abs(tmp[,2]) <= 1),]
  ans <- tmp1[sample(nrow(tmp1),10),]
  ans

Peter Ehlers

> Thanks in advance for your help.
>
> Kind Regards
>
> Anup
>



More information about the R-help mailing list