vendredi 22 septembre 2023

a fast way to generate true-false matrix based on random sampling with a matrix of probability values

I have a n × n matrix in which values are between [0,1] and each column has the same values.

These values represent probabilities for each element of the matrix to take the value TRUE or FALSE.

I am searching for a fast way to transform the matrix with the probabilities to a matrix with TRUE/FALSE values based on an independent random sample for each element.

Currently, this code generates what I want (the tf_matrix):

n <- 10
p_true <- runif(n,0,1)

p_matrix <- matrix(p_true,n,n, byrow=T)
tf_matrix <- matrix(F, n,n)

for(i in 1:nrow(tf_matrix)) {
    
    for(j in 1:ncol(tf_matrix)) {
        
        tf_matrix[i,j] <- sample(c(T,F), size = 1, prob = c(p_matrix[i,j], 1-p_matrix[i,j]))
        
    }
}

However, this is likely very slow, as it uses two for-loops and I need to do this over and over for a large matrix.

Is there a way to make this more efficient (i.e., as fast as possible)?




Aucun commentaire:

Enregistrer un commentaire