[R] sample function with different proportions

(Ted Harding) ted.harding at wlandres.net
Tue Jul 5 20:37:09 CEST 2011


Well, you can have exactly 70:30%, i.e. 70% 1s and 30% 0s, but
in random order. For example:

  Popn <- c(rep(1,70),rep(0,30))
  Samp <- sample(Pop)

(see '?sample' for this usage -- the result of sample(x) is a
random permutation of the elements of x).

In probabilistic terms, this is a "conditional" sample, i.e.
what you would get by using sample(...,replace=TRUE) but
rejecting samples which do not have 70% 1s and 30% 0s until
you get a sample which does.

Ted.

On 05-Jul-11 18:25:48, Joshua Wiley wrote:
> Hi Ana,
> 
> Look at the documentation for ?sample, specifically, the "prob"
> argument.  In your case this should work:
> 
> sample(c(0,1), 100, replace = TRUE, prob = c(.3, .7))
> 
> note that you may not have *exactly* 70% 1 and 30%, in any given
> sample.
> 
> HTH,
> 
> Josh
> 
> On Tue, Jul 5, 2011 at 11:21 AM, Ana Kolar <annakolar at yahoo.com> wrote:
>> Hi there,
>>
>> I guess this is an easy one, but still:
>>
>> I would like to randomly sample 0s and 1s but in a way that
>> I end up having for example 70% of 1s and the rest of 0s and
>> not 50:50 as this function does: sample(c(0,1), 100, replace = TRUE)
>>
>> Any recommendations?
>>
>> Many thanks!
>> Ana

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at wlandres.net>
Fax-to-email: +44 (0)870 094 0861
Date: 05-Jul-11                                       Time: 19:37:06
------------------------------ XFMail ------------------------------



More information about the R-help mailing list