0

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

2
  • Changing the first line of the function to vals <- sample(0:1, n*(n-1)/2, rep = T, prob=c(0.1,0.9)) works for me. Commented Apr 10, 2014 at 0:54
  • possible duplicate of Weighted random number generation in R Commented Apr 10, 2014 at 0:56

1 Answer 1

1

You should look in to help page of sample function

?sample shows :

Usage

sample(x, size, replace = FALSE, prob = NULL)

where

prob
A vector of probability weights for obtaining the elements of the vector being sampled.

and further below in Details you will see

The optional prob argument can be used to give a vector of weights for obtaining the elements of the vector being sampled. They need not sum to one, but they should be non-negative and not all zero.

So to answer your question, apart from read the manual , use prob=c(0.1,0.9) if you want probability of 0.1 for first element of x and 0.9 for the second.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.