Re: [R] generate 3 distinct random samples without replacement

From: Sarah Goslee <>
Date: Mon, 07 Mar 2011 15:18:55 -0500

Cesar, your indexing is wrong:

On Mon, Mar 7, 2011 at 2:17 PM, Cesar Hincapiť <> wrote:
> Hello:
> I wonder if I could get a little help with random sampling in R.
> I have a vector of length 7375. †I would like to draw 3 distinct random samples, each of length 100 without replacement. †I have tried the following:
> d1 <- 1:7375
> set.seed(7)
> i <- sample(d1, 100, replace=F)
> s1 <- sort(d1[i])
> s1

d1 is a continuous vector of integers, 1 thru 7375 and of length 7375

> d2 <- d1[-i]

but you've taken out 100 of those numbers, so d2 is now of length 7275 and has gaps in the sequence.

> set.seed(77)
> j <- sample(d2, 100, replace=F)
> s2 <- sort(d2[j])
> s2

j is a sample *of the values* and those values are no longer the indices of the vector d2

You need instead
j <- sample(1:length(d2), 100, replace=FALSE) s2 <- sort(d2[j])

Some of the value in j no longer exist in d2 as indices. 7375 could be selected, but since d2 only has 7275 elements d2[7375] doesn't return anything (actually NA).

Same for your third sample, only the indices are even less like the elements of the vector because you've removed another random set of values.


Sarah Goslee

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Mon 07 Mar 2011 - 20:22:26 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 07 Mar 2011 - 20:40:19 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive