[R] Vector with zeros and ones

Marc Schwartz marc_schwartz at me.com
Tue Apr 23 01:28:12 CEST 2013


On Apr 22, 2013, at 6:21 PM, Ayyappa <ayyappach at gmail.com> wrote:

> Dear group,
> 
> I want to generate a vector of 10 elements that always has 20% zeroes, but with a random ordering of zeroes and ones. Can you please suggest a function to do that in R? I tried 'sample' function but the 20% zeros was not always guaranteed.
> 
> Thanks for your help.
> 
> Regards,
> Ayyappa


Predefine your source vector with the fixed distribution that you desire:

Vec <- c(rep(0, 2), rep(1, 8))

> Vec
 [1] 0 0 1 1 1 1 1 1 1 1

Then sample() from that vector:

set.seed(1)

> sample(Vec)
 [1] 1 1 1 1 0 1 1 1 1 0

> sample(Vec)
 [1] 1 0 1 1 1 1 1 1 0 1

> sample(Vec)
 [1] 1 0 1 0 1 1 1 1 1 1

> sample(Vec)
 [1] 1 1 1 0 1 1 1 0 1 1


Regards,

Marc Schwartz



More information about the R-help mailing list