# Bernoulli trials with probability matrix

Hello everybody,

I'm fairly new to RStudio and I wondered if a function is available that performs a random Bernoulli trial from a given probability matrix. So I've got a 15.000 by 5 matrix with probabilities and I want to turn all of these probabilities into a single binary outcome so that my output will be a 15.000 by 5 matrix as well. For instance, if the first element of my probability matrix is 0.8, the first element of my output matrix will be 1 with a probability of 0.8. I know RStudio contains a function rbinom that produces this outcome for 1 element, but I only get a scalar outcome when I insert my probability matrix in this function.

I know MATLAB has this function called binornd that produces this outcome for a given matrix.

I hope you can help me with this issue.

Here is one approach.

``````set.seed(123)
MAT <- matrix(runif(25), nrow = 5)
MAT
[,1]      [,2]      [,3]       [,4]      [,5]
[1,] 0.2875775 0.0455565 0.9568333 0.89982497 0.8895393
[2,] 0.7883051 0.5281055 0.4533342 0.24608773 0.6928034
[3,] 0.4089769 0.8924190 0.6775706 0.04205953 0.6405068
[4,] 0.8830174 0.5514350 0.5726334 0.32792072 0.9942698
[5,] 0.9404673 0.4566147 0.1029247 0.95450365 0.6557058

BINOM <- function(P) rbinom(n = 1, size = 1, prob = P)
apply(X = MAT, MARGIN = c(1,2), BINOM)
[,1] [,2] [,3] [,4] [,5]
[1,]    0    1    1    1    1
[2,]    1    0    1    0    1
[3,]    1    1    1    0    1
[4,]    1    0    1    0    1
[5,]    1    0    0    1    0
``````

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.