[R] Generating a new matrix using rbinom and a matrix of probabilities.

Economics Guy economics.guy at gmail.com
Tue Mar 11 16:15:44 CET 2008


I am having a little trouble getting R to do something without writing
a couple of very awkward loops.

I have a matrix of probabilities and I want to generate a new matrix
of ones and zeros where each element in the new matrix is the result
of a draw from a binomial distribution where the probability of
getting a 1 is the corresponding element in the matrix of
probabilities.

Example Code:
--------------------------------------------

## First I generate the matrix of probabilities for example purposes.

probMatrix <- matrix(NA,5,5){

for (i in 1:5)

probVectorI <- runif(5,0,1)

probMatrix[i,] <- probVectorI

}

# Now I want to take each element in probMatrix and use it as the
probability parameter in rbinom draw and generate a new matrix.
Something like this:

binomialMatrix <- rbinom(1,1,probMatrix)

# But that does not work. I know I can run a loop across each vector
of the matrix, but this seems like an bad way to do this.

---------------------------End Code--------------------------------

So any help would be appreciated.

Thanks,

EG



More information about the R-help mailing list