Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: looking for a more efficient way of running rbinom() taking probabilities from a large matrix

I have a 20000×90 matrix M of probabilities ranging between 0 and 1. I want to use these probabilities to return a 20000×90 matrix of 1’s and 0’s (i.e. for each probability p in the matrix I want to run rbinom(1,1,p)).

This is my current solution which works:

apply(M,1:2,function(x) rbinom(1,1,x))

However, it is quite slow and I am wondering if there is a faster way of achieving the same thing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

rbinom is vectorised, so you can pass the vector (or matrix) of probabilities; you just need to change the n, the number of observations, from 1 to the number of values in M.

An example:

# with loop
set.seed(74309281)
M = matrix(runif(20000*90), nr=20000, nc=90)
a1 = apply(M,1:2,function(x) rbinom(1,1,x))

# without loop
set.seed(74309281)
M = matrix(runif(20000*90), nr=20000, nc=90)
a2 = matrix(rbinom(length(M),1,M), nr=nrow(M), nc=ncol(M))

all.equal(a1, a2)
# [1] TRUE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading