简体   繁体   中英

How to sample from the binomial distribution given a probability matrix

I am trying to create a matrix of 0s, 1s and 2s. Let's call this dataset A such that A[i,j] ~ Binomial(2, P[i,j]) , where P is another matrix that gives the probabilities of each entry in A . So, each entry in the matrix A will be binomially distributed according to its corresponding probability entry in matrix P . The following gives a for-loop that illustrates what I want but this is really slow in R, so I was thinking if anyone knows how I can do it with the apply function? Both P and A are m*n matrices.

for (i in 1:m) {
  for (j in 1:n) {
    a[i,j] = rbinom(n = 1, size = 2, prob = p[i,j])
  }
}
prow <- 100
pcol <- 100
set.seed(1)
p <- matrix(runif(prow*pcol), ncol=pcol, nrow=prow)
diag(p) <- 0
a <- matrix(NA, ncol=pcol, nrow=prow)

a[] <- rbinom(n=prow*pcol, size=2, prob = p)

print(a[1:10,1:10])

The probability parameter can be vectorized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM