I mentioned in an earlier post (Am I inconsistent?) that I got interested in R because Amy had asked me to help her with some sampling at one point. Since that was my starting point, I thought I would share some of my experiments with you.
In this post:
- Simple random sampling
- Simple random sampling with a seed
- Sorting your sample
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | > # Sample 30 from 1 to 300 > sample(300, 30) [1] 44 200 258 290 165 132 287 70 118 241 11 191 194 192 [15] 127 143 55 217 49 130 263 203 26 46 251 142 72 107 [29] 77 31 > # A second time > sample(300, 30) [1] 101 108 25 289 257 102 110 45 173 197 202 168 134 225 [15] 184 155 226 68 86 51 90 204 159 263 245 201 213 169 [29] 127 11 > # What about a replicable sample? > set.seed(123) > sample(300, 30) [1] 87 236 122 263 279 14 156 262 162 133 278 132 196 165 [15] 30 257 70 12 93 269 250 194 179 276 181 195 150 163 [29] 79 40 > # A second time > set.seed(123) > sample(300, 30) [1] 87 236 122 263 279 14 156 262 162 133 278 132 196 165 [15] 30 257 70 12 93 269 250 194 179 276 181 195 150 163 [29] 79 40 > # Can we sort the output to make the result easy to see? > set.seed(123) > sort(sample(300, 30)) [1] 12 14 30 40 70 79 87 93 122 132 133 150 156 162 [15] 163 165 179 181 194 195 196 236 250 257 262 263 269 276 [29] 278 279 |
What is “set.seed” for?
The “set.seed” function in R can help when you want to verify or replicate a sample. In this case, the seed I used was “123″ (but it can be any number you want it to be). So, if you run the same sample with the same seed in R, you should get the same results as me. If you ran the same sample without a seed, each time, you would get a different result.
Disclaimer: I’m not by any measures an expert in R. I have just been experimenting with the software. By the way, if you want to experiment with any of the code I mention here, you can first download R, copy the code, and in R, go to “Edit > Paste commands only”.
Related posts (possibly):
- Stratified Random Sampling in R–A Function in Progress IMPORTANT: This is here mostly to remind me of how...
- Stratified random sampling in R from a data frame After a little bit more work, there’s a new stratified...
- Sampling with replacement in R In my last post about sampling (Simple sampling with R)...
- R is like a giant calculator for grownups One of the things that is interesting about R is...
- Getting data into R When you first open R, you’re greeted with a screen...

Pingback: R is like a giant calculator for grownups