Search code examples
rfor-loopmatrixlapplyadjacency-matrix

How to fill a matrix by proportion?


I'm trying to create aa 20x20 matrix filled with numbers from -1:2. However, I don't want it to be random but by proportion that I decide.

For example, I would want 0.10 of the cells to be -1, 0.60 to be 0, 0.20 to be 1, 0.10 to be 2.

This code was able to get me a matrix with all of the values I want, but I don't know how to edit it to specify the proportion of each value I want.

r <- 20
c <- 20
mat <- matrix(sample(-1:2,r*c, replace=TRUE),r,c)

Solution

  • We can use the prob argument from sample

    matrix(sample(-1:2,r*c, replace=TRUE, prob = c(0.1, 0.6, 0.2, 0.2)), r, c)