Creating a matrix with random entries with given probabilities in R

Viewed 102

I want to create a 100x100 matrix A with entry a_ij being randomly selected from the set {0,1} with P(a_ij=1)=0.2 and P(a_ij=0)=0.8.

This is what I’ve tried so far:

n<-100
matrix<-matrix(0,100,100)
mynumbers<-c(1,0)
myprobs<-c(0.2,0.8)
for(i in 1:100){
  for (j in 1:100){
    matrix[i,j]<-sample(mynumbers, 1, replace=TRUE, prob=myprobs)
  }
}
matrix

I’m not sure about the sample size being 1, but this way only seems to work if I choose size=1... Is this the correct way to do it? Thank you in advance!

1 Answers

As @akrun noted there are much easier ways. A matrix of 100 x 100 means 10,000 entries. prob = .2 is saying success = 1 = P(a_ij=1)=0.2, size in this case means one trial at a time. The matrix parameters should be pretty self-evident.

set.seed(2020)
trials <- rbinom(n = 10000, size = 1, prob = .2)
my.matrix <- matrix(trials, nrow = 100, ncol = 100)

or to more closely resemble your code

n <- 10000
mynumbers<-c(1,0)
myprobs<-c(0.2,0.8)
trials2 <- sample(x = mynumbers, 
                  size = n, 
                  replace = TRUE, 
                  prob = myprobs)
my.matrix2 <- matrix(trials2, nrow = 100, ncol = 100)
Related