0

I want to create a matrix in R with element [-1,0,1] with probability [1/6, 2/3, 1/6] respectively. The probability may change during runtime. for static probability I have got the output but the problem is dynamic change in the probability. for example, If I create a matrix for the above probability with [sqrt(3),0,-sqrt(3)], the required output is.

Note: The Probability should not be static as mentioned. It may vary during runtime.

Kindly help to solve this.

enter image description here

Siddhu
  • 1,188
  • 2
  • 14
  • 24

2 Answers2

3

Supposing you want a 2x3 matrix:

matrix(sample(c(-1,0,1), size=6, replace=TRUE, prob=c(1/6,2/3,1/6)), nrow=2)

So you sample from the values you want, with probabilities defined in prob. This is just a vector, but you can make it into a matrix of the desired shape using matrix afterwards. Replace the probabilities by a variable instead of values to not make it static.

If the numbers should be distributed according to a certain scheme rather than randomly drawn according to a probability, replicate the vector elements and shuffle them:

 matrix(sample(rep(c(-1,0,1), times=c(1,4,1))), nrow=2)
mpjdem
  • 1,504
  • 9
  • 14
  • Thank you @mpjdem, but the output gives 3 zeros, 2 (-1) and 1 (+1). I need 4 zeros according to condition – Siddhu Dec 23 '16 at 12:57
  • 2
    It's a probability, so it's not deterministic. For what you want, you would need the `rep` function with the `times` argument, and then use `sample`on it to shuffle it. I'll quickly write it up. – mpjdem Dec 23 '16 at 13:03
  • Yeah I understand, Thank you – Siddhu Dec 23 '16 at 13:04
1

You can try this to generate a mxn matrix:

sample.dynamic.matrix <- function(pop.symbols, probs, m, n) {
   samples <- sample(pop.symbols, m*n, prob = probs, replace=TRUE)
   return(matrix(samples, nrow=m))
}

set.seed(123)
sample.dynamic.matrix(-1:1, c(1/6,2/3,1/6), 2, 3)
#     [,1] [,2] [,3]
#[1,]    0    0   -1
#[2,]    1   -1    0
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63