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
- n: The number of random values you want to generate.
- min: The minimum value of the distribution (inclusive). The default is 0.
- 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
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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.