I need to split an interval into n
equal length buckets and then allocate a uniformly distributed random number into the corresponding bucket. The function should return the index of the bucket the random number is allocated to. Here's what I have so far. I'm looking for something more efficient than this, as the same operation needs to be carried out for each element of a large matrix:
bucket.index <- function(n, i=1, l=0, u=1)
{
set.seed(i)
num <- runif(1, min=l, max=u)
bucket.length <- (u-l)/n
buckets <- seq(l+bucket.length, u, bucket.length)
return (which(num < buckets)[1])
}
bucket.index(n)
Thanks
Aucun commentaire:
Enregistrer un commentaire