R runif() Function

R runif() function is used to generate random numbers from a uniform distribution, which means each number within the specified range has an equal probability of being drawn.

Syntax

runif(n, min = 0, max = 1)

Parameters

  1. n: The number of random values you want to generate.
  2. min: The minimum value of the distribution (inclusive). The default is 0.
  3. max: The maximum value of the distribution (exclusive). The default is 1.

Example 1: Generating a Single Uniform Random Number

set.seed(123) # Setting a seed for reproducibility

one_random_value <- runif(1)

print(one_random_value)

Output

[1] 0.2875775

Example 2: Generate 10 uniformly distributed random

Generating 10 uniformly distributed random numbers from 0 to 1 

set.seed(123)

random_numbers <- runif(10, min = 0, max = 1)

print(random_numbers)

Output

[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673 0.0455565 0.5281055
[8] 0.8924190 0.5514350 0.4566147

Example 3: Generating random numbers from a specified range

Generating random numbers from a specified range

set.seed(123)

random_numbers <- runif(5, min = 15, max = 25)

print(random_numbers)

Output

[1] 17.87578  22.88305  19.08977  23.83017  24.40467

Difference between runif() and rnorm() function

The main difference between runif() and rnorm() is that the runif() function generates random numbers from a uniform distribution, while the rnorm() function generates random numbers from a normal distribution.

Leave a Comment