1
2
3
4
5
#

R: Sampling & Simulation - Intro

I. Sampling
Randomly sample 1 though 10.
> x = 1:10
> x
[1]  1  2  3  4  5  6  7  8  9 10
>
> sample(x)
[1]  6  2  9  7  5 10  8  1  4  3

Now, lets roll a six sided die once.

> die = 1:6
> sample(die, 1)
[1] 3

Now, lets randomly sample 3 numbers from 1 through 8. For this activity, there are two functions that you could use: sample() or sample.int(). Howver, the function sample.int() is a little quicker. Also, notice how the two outputs are different. This is due to the fact that we are asking R to randomly sample 3 numbers, so we shouldn't expect the numbers to be the same.

> ### METHOD 1 - USE sample() function
> x = 1:8
>
> # randomly sample 3 from 1 though 8
> sample(x, 3)
[1] 4 7 8
>
> ### METHOD 2 - USE sample.int() function
> # randomly sample 3 from 1 through 8
> # same process as above.. just easier :)
> sample.int(10, 3)
[1] 8 5 6

Example

Kate wishes to conduct a survey that required a simple random sample from the 20 students in her class. A simple random sample ensures that every individual is just as likely to be chosen as any other student. The list of the 20 students in Kate's class are listed below.

 Mary Jake Irving Isabel Dan Andres Sophia Kate Ryan Ann Larry Vanessa Winston Liz Paul Hillary Adriana Ben Sam Chris

Kate began the process by giving each student a unique number. She did this by labeling each student with a number, 1 through 20.

 1 Mary 5 Jake 9 Irving 13 Isabel 17 Dan 2 Andres 6 Sophia 10 Kate 14 Ryan 18 Ann 3 Larry 7 Vanessa 11 Winston 15 Liz 19 Paul 4 Hillary 8 Adriana 12 Ben 16 Sam 20 Chris

She then ran the following R code which randomly sampled 5 numbers from 1 through 20.

> sample(1:20, 5)
[1] 20 12  5 13  7

Kate then highlighted the names that corresponded to the 5 numbers randomly chosen from R.

 1 Mary 5 Jake 9 Irving 13 Isabel 17 Dan 2 Andres 6 Sophia 10 Kate 14 Ryan 18 Ann 3 Larry 7 Vanessa 11 Winston 15 Liz 19 Paul 4 Hillary 8 Adriana 12 Ben 16 Sam 20 Chris

With the names in hand, Kate set out to survey Jake, Vanessa, Ben, Isabel, and Chris.

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.