Open In App

How to Generate Random Numbers in R

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Random number generation is a process of creating a sequence of numbers that don't follow any predictable pattern. They are widely used in simulations, cryptography and statistical modeling. R Programming Language contains various functions to generate random numbers from different distributions like uniform, normal and binomial.

Setting a Seed for Reproducibility

R's random number generation is based on a pseudo-random number generator. This means the numbers generated are not truly random but follow a predictable pattern determined by a seed. Using a seed allows you to reproduce the same sequence of random numbers across different runs. We can set a seed using the set.seed() function.

R provides functions to generate random numbers from different statistical distributions. We will explore some common distributions and their respective functions.

1. Using Uniform Distribution

The runif() function generates random numbers from a uniform distribution. It can be used to generate random number between 0 and 1. Where all values between a given range have an equal probability of occurring. Below is the syntax:

runif(n, min, max)

Where:

  • n: Number of random numbers to generate.
  • min: Minimum value (default is 0).
  • max: Maximum value (default is 1).
R
runif(1,0,1) 

Output:

0.6928034061566

2. Using Normal Distribution

The rnorm() function generates random numbers from a normal (Gaussian) distribution with a specified mean and standard deviation. Below is the syntax:

rnorm(n, mean, sd)

Where:

  • n: Number of random values.
  • mean: Mean of the distribution (default is 0).
  • sd: Standard deviation (default is 1).
R
rnorm(1, mean = 0, sd = 1)

Output:

0.359813827057364

3. Using Binomial Distribution

The rbinom() function generates random numbers from a binomial distribution which models the number of successes in a fixed number of trials. Below is the syntax:

rbinom(n, size, prob)

Where:

  • n: Number of random values.
  • size: Number of trials.
  • prob: Probability of success in each trial.
R
rbinom(1, size = 10, prob = 0.5)

Output:

6

4. Generating Random Integers

The sample() function is commonly used to generate random integers by sampling from a specified range. Below is the syntax:

sample(x, size, replace = FALSE)

Where:

  • x: Vector of numbers to sample from.
  • size: Number of values to return.
  • replace: Whether sampling should be with replacement (default is FALSE).
Python
sample(1:100, 1)

Output:

99

In this article we covered several methods for generating random numbers in R including uniform distribution, normal distribution, binomial distribution and random integers. By setting a seed, you can ensure reproducibility, which is crucial in scientific research and data analysis.


Article Tags :

Similar Reads