Generate Set of Random Integers from Interval in R (2 Examples)


In this article, I’ll demonstrate how to sample random integers from an interval in the R programming language.

The content of the page is structured as follows:

Let’s just jump right in:


Example 1: Sample Random Integers from Range without Replacement

The following R programming syntax demonstrates how to generate a set of unique random integers (i.e. sampling without replacement).

As a first step, we should set a random seed for reproducibility:

set.seed(2893755)                # Set random seed

In the next step, we can apply the function to draw random integers in a certain range. Within the function, we are specifying a range between 1 and 10 (i.e. n = 10) and a sample size of 5 (i.e. size = 5):

my_int1 <- = 10,    # Generate random integers
                      size = 5)
my_int1                          # Print vector of random integers
# [1] 9 5 3 7 8

The previous vector shows our result: We have created a vector with a length of 5 containing random integers.


Example 2: Sample Random Integers from Range with Replacement

The following R code shows how to draw random integers with replacement.

For this, we have to specify replace = TRUE within the function:

my_int2 <- = 10,    # Generate random integers
                      size = 5,
                      replace = TRUE)
my_int2                          # Print vector of random integers
# [1] 9 9 3 1 4

As you can see based on the previous output, we have created another vector containing five random integers. The value 9 has been drawn twice.


Video, Further Resources & Summary

I have recently released a video on my YouTube channel, which illustrates the contents of this tutorial. You can find the video below:


Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.


Also, you might read some of the other tutorials on this website:


At this point you should have learned how to sample random integers from a range in the R programming language. In case you have additional questions, don’t hesitate to let me know in the comments below.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.