The binomial code works very well. Thanks for this very much!
Have a nice day.
Jeff
? 8/27/2012 1:25 PM, Rui Barradas ??:
Hello,
Try the following.
set.seed(1)
X <- rbeta(2*length(shape1), rep(shape1, each = 2), rep(shape2, each
= 2))
X <- matrix(X, ncol = 2, byrow = TRUE)
#-- binomial
n <- 10
p <- runif(10000)
Y1 <- matrix(nrow = 10000, ncol = 10)
set.seed(6292)
for(i in 1:10000){
Y1[i, ] <- rbinom(n, 2, p[i])
}
set.seed(6292)
Y2 <- rbinom(n*length(p), 2, rep(p, each = 10))
Y2 <- matrix(Y2, ncol = n, byrow = TRUE)
identical(Y1, Y2) #TRUE
The trick is not to use argument recycling.
Hope this helps,
Rui Barradas
Em 27-08-2012 15:49, JeffND escreveu:
Hi folks,
I have a question about how to efficiently produce random numbers
from Beta
and Binomial distributions.
For Beta distribution, suppose we have two shape vectors shape1 and
shape2.
I hope to generate a 10000 x 2 matrix X whose i th rwo is a sample from
reta(2,shape1[i]mshape2[i]). Of course this can be done via loops:
for(i in 1:10000)
{
X[i,]=rbeta(2,shape1[i],shape2[i])
}
However, the above code is time consuming. It would be better to
directly
generate X without any loops. I tried the following code
X<- rbeta(2,shape1,shape2)
but it looks not right. So I was wondering if there is an R code
doing this.
For Binomial distribution, I have a similar question. I hope to
generate a
10000 x n matrix Y whose i th row is a sample from rbinom(n,2,p[i]),
where p
is a vector of binomial probabilities. We can also do it by loops
for(i in 1:10000)
{
Y[i,]=rbinom(n,2,p[i])
}
But it would be nice to do it without using any loops. Is this
possible in
R?
Many thanks for great help and suggestions!
Jeff
--
View this message in context:
http://r.789695.n4.nabble.com/How-to-generate-a-matrix-of-Beta-or-Binomial-distribution-tp4641422.html
Sent from the R help mailing list archive at Nabble.com.