Home > Mobile >  How to generate a series of number by function of sample in R, with given different probability in e
How to generate a series of number by function of sample in R, with given different probability in e

Time:12-14

For example I have a vector about possibility is

myprob <- (0.58, 0.51, 0.48, 0.46, 0.62)

And I want to sampling a series of number between 1 and 0 each time by the probability of c(1-myprob, myprob),

which means in the first number in the series, the function sample 1 and 0 by (0.42, 0.58), the second by (0.49, 0.50) and so on,

how can I generate the 5 numbers by sample?

The syntax of

Y <- sample(c(1,0), 1, replace=F, prob=c(1-myprob, prob))

would have incorrect number of probabilities and only 1 number output if I specify the prob;

while the syntax of

Y <- sample(c(1,0), 5, replace=F, prob=c(1-myprob, prob))

would have the probabilities focus on only 0.62(or not I am not sure, but the results seems not correct at all)

Thanks for any reply in advance!

CodePudding user response:

If myprob is the probability of drawing 1 for each iteration, then you can use rbinom, with n = 5 and size = 1 (5 iterations of a 1-0 draw).

set.seed(2)
rbinom(n = 5, size = 1, prob = myprob)
[1] 1 0 1 0 0

CodePudding user response:

Maël already proposed a great solution sampling from a binomial distribution. There are probably many more alternatives and I just wanted to suggest two of them:

runif()

as.integer(runif(5) > myprob)

This will first generate a series of 5 uniformly distributed random numbers between 0 and 1, then compare that vector against myprob and convert the logical values TRUE/FALSE to 1/0.

vapply(sample())

vapply(myprob, function(p) sample(1:0, 1, prob = c(1-p, p)), integer(1))

This is what you may have been looking for in the first place. This executes the sample() command by iterating over the values of myprob as p and returns the 5 draws as a vector.

  • Related