pc8807 pc8807 - 1 year ago 75
R Question

Generating a Sample of n i.i.d Bernoulli Variables in R

I'm trying to write a function in R which produces a set of n i.i.d Bernoulli random variables X1,X2,...,Xn ∼ B(1,π).

To generate M = 1000 random samples. When n = 10 and pi = 0.4.

I'm having trouble starting the code. If anyone could help out that would be greatly appreciated.

Here is what I have run to this point:


Now I want to assemble those variables into a matrix of 1000 of those samples run through the

Answer Source

Taking what you've done so far:

set.seed(101) ## for reproducibility
rr <- replicate(1000,rbinom(n=10,prob=.04,size=1))

creates 1000 samples.

## [1] 10 1000
## [1] 0.0411

i.e. this is 10 rows x 1000 columns; you can use t() to transpose it if you like. If you specify simplify=FALSE in the replicate() call you'd get a list of vectors of length 10 instead.

(Your question is inconsistent as to whether you want probability of 0.04 or 0.4, but you should be able to sort that out for yourself.)

For this particular question you could also use



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download