Generating random samples

In this section, we will introduce how to generate random samples from a given population with the sample and sample.int functions.

Getting ready

In this recipe, you need to prepare your environment with R installed.

How to do it…

Please perform the following steps to generate random samples.

  1. First, generate random samples from 1 to 10:
    > sample(10)
    
  2. If you would like to reproduce the same samples, you can set the random seed beforehand:
    > set.seed(123)
    > sample(10)
     [1]  3  8  4  7  6  1 10  9  2  5
    
  3. You can then randomly choose two samples from 1 to 10:
    > sample(10,2)
    [1] 10  5
    
  4. If the population and sample size are required arguments, you can also use the sample.int function:
    > sample.int(10,size=2)
    [1] 7 6
    
  5. For example, one can simulate ...

Get R for Data Science Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.