Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top