1

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])
  }
}
mdy
  • 43
  • 5
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Provide a sample `P` matrix to be used for testing. – MrFlick Apr 25 '19 at 19:43

1 Answers1

0
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.

thc
  • 9,527
  • 1
  • 24
  • 39