[R] sampling without repetition
Tony Plate
tplate at acm.org
Tue Nov 18 02:24:41 CET 2003
> r <- 1:30
> # Random allocation to sets
> tapply(r, sample(1:3,length(r),rep=T), c)
$"1"
[1] 1 3 8 12 15 16 18 20 21 25 29
$"2"
[1] 2 5 6 7 9 10 13 14 17 19 22 27 30
$"3"
[1] 4 11 23 24 26 28
> # Equal size sets (approximately)
> tapply(r, sample(seq(length(r))%%3), c)
$"0"
[1] 1 6 9 10 12 15 22 24 28 30
$"1"
[1] 2 3 4 5 8 17 18 21 23 27
$"2"
[1] 7 11 13 14 16 19 20 25 26 29
>
At Monday 07:28 PM 11/17/2003 -0500, you wrote:
>Hi,
> I'm trying to write a function that will divide a given range of
>numbers into 3 sets using sample(), without repetition. Currently I'm
>trying this approach:
>
>r <- 1:10
>s1 <- sample(r,size=3)
>
>Next, I want to remove the selected elements from r and sample() from
>the remainder.
>
>r <- r[ -(r=s1) ]
>s2 <- sample(r,size=3)
>
>When I go to remove the elements contained in s2 from r I get an error:
>
>r <- r[ -(r=s2) ]
>Error: subscript out of bounds
>
>I'm not sure why this is happening. I tried replacing the '=' with '=='
>but I get another error
>
>Warning message:
>longer object length
> is not a multiple of shorter object length in: r == s1
>
>Essentially what I need is to get the indices into r of the elements of
>s1 & s2. I have looked at which but I cant seem to work out how I can
>get the indices into r of all the elements of, say, s1.
>
>Does anybody have any suggestions? (Of course if there is a more elegant
>way of doing this whole thing I would appreciate any pointers)
>
>Thanks,
>
>-------------------------------------------------------------------
>Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
>GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
>-------------------------------------------------------------------
>A committee is a life form with six or more legs and no brain.
>-- Lazarus Long, "Time Enough For Love"
>
>______________________________________________
>R-help at stat.math.ethz.ch mailing list
>https://www.stat.math.ethz.ch/mailman/listinfo/r-help
Tony Plate tplate at acm.org
More information about the R-help
mailing list