I have been recently helped in getting a function to write a random binary matrix, with the condition that the diagonal is 0s.
fun <- function(n){ vals <- sample(0:1, n*(n-1)/2, rep = T) mat <- matrix(0, n, n) mat[upper.tri(mat)] <- vals mat[lower.tri(mat)] <- vals mat } Here I am entering values from the 'sample' to the upper and lower triangle separately. I would like to keep this in any updated function because sometimes I may wish to enter transpositions of each triangle into the other.
What I would like assistance with is how to change the frequency of 1s in the random matrix. This already varies around, I believe, a normal distribution. e.g. in a 9x9 matrix, there are 81-9=72 cells to fill, and the average number of 1s used is 36.
However, if I wanted to create matrices with a probability of e.g. p=0.9 of there being a 1, or e.g. p=0.2 of there being a 1... - how is this done?
I tried some ways of changing the sample(0:1,) part of the code by adding in probability functions but I only got errors.
Thanks
vals <- sample(0:1, n*(n-1)/2, rep = T, prob=c(0.1,0.9))works for me.