Q:

How to create a matrix with probability distribution in R

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. 

A:

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)

