Skip to content

Selecting a random sample

2 messages · Scot W McNary, Brian Ripley

#
Hi,

I'm trying to learn R and get an errand done at the same time.  I have a
list of cases with ids numbered sequentially 1 to 403.  I want to select
at random exactly 20 without replacement.  Here's what I've tried so far:
This works, but I can have anywhere from 16 to 32 cases in the subset
'who', due to random variability in the runif generator.  What's a more
efficient (and general) way to extract a subset of exactly n from a total
sample N?

Thanks in advance,

Scot


--
  Scot W. McNary  email:smcnary at charm.net   

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On Mon, 22 May 2000, Scot W McNary wrote:

            
sample(N, n, replace=F)

Easy?  See ?sample for variations on the theme.

By the way, seq(N)[runif(N) < n/N] would have done it your way in
simpler code, and 

seq(N)[rank(runif(N)) <= n]

is another general solution.