[R] Sample a vector repeatedly
Marc Schwartz
marc_schwartz at me.com
Mon Sep 13 19:04:57 CEST 2010
On Sep 13, 2010, at 10:30 AM, James Hudson wrote:
> I‚d like to sample the vector „y‰ repeatedly. In this dummy dataset, I‚d
> like to sample (and store) it 1, 2, and 3 times.
>
> Is there a straightforward way to do this without using a „for‰ loop?
>
> x <- c(1 :3)
>
> y <- c(1:10)
>
> (run.sample <- sample (y, x))
>
> Thanks very much,
>
> James Hudson
When you say "1, 2 and 3 times", do you mean that you want 1, 2 and 3 elements from 'y' randomly sampled:
set.seed(1)
> sapply(x, function(i) sample(y, i))
[[1]]
[1] 3
[[2]]
[1] 4 6
[[3]]
[1] 10 2 8
Or, do you want the entire 'y' vector permuted 1, 2 and 3 times:
set.seed(1)
> sapply(x, function(i) replicate(i, sample(y)))
[[1]]
[,1]
[1,] 3
[2,] 4
[3,] 5
[4,] 7
[5,] 2
[6,] 8
[7,] 9
[8,] 6
[9,] 10
[10,] 1
[[2]]
[,1] [,2]
[1,] 3 10
[2,] 2 2
[3,] 6 6
[4,] 10 1
[5,] 5 9
[6,] 7 8
[7,] 8 7
[8,] 4 5
[9,] 1 3
[10,] 9 4
[[3]]
[,1] [,2] [,3]
[1,] 5 9 5
[2,] 6 6 8
[3,] 4 7 4
[4,] 2 4 2
[5,] 10 8 1
[6,] 8 10 6
[7,] 9 1 7
[8,] 1 2 9
[9,] 7 3 3
[10,] 3 5 10
I am guessing the first scenario, but included the second just in case.
See ?sapply in which help for both sapply() and replicate() is available.
HTH,
Marc Schwartz
More information about the R-help
mailing list