简体   繁体   中英

how to generate a random number based on probability in r

I'm trying to create a markov chain, and want to select number in a list based on probability, which could be any number.for example, l represents the probability from 1-1 1-2 and 1-3. m represents the probability from 2-1, 2-2 and 2-3. n represents the probability from 3-1,3-2,3-3.

l=c(1/3,1/3,1/3)
m=c(2/5,3/5,0)
n=c(1/7,0,6/7)

the sequence start from 1 and end from 3 I may generate different lists of number based on the different chance. for example (1,3),(1,2,2,1,3)(1,2,2,1,1,3)etc.

Does anyone know whether there's a function in R could generate a number based on probability? Thanks a lot.

If you want to start with a simple function that samples from a range of numbers mynumbers with a given probability myprob , you could use the base R sample function:

 mynumbers = c(1,2) #you numbers to sample from
 myprob = c(.25, .75) #your probabilities
 d = sample(mynumbers,
       size = 1000, #1000 times sampled from `mynumbers`
       replace = T,
       prob = myprob)

table(d) #This should show you the approximate probability of `myprob`

Does this help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM