Generating random numbers
If you just need to generate basic random numbers in R, you can use the following simple
methods:
1. Random Numbers from a Uniform Distribution (Default Range)
R
Копировать код
runif(n)
Example: Generate 5 random numbers between 0 and 1:
R
Копировать код
runif(5)
2. Random Numbers from a Uniform Distribution (Custom Range)
R
Копировать код
runif(n, min, max)
Example: Generate 5 random numbers between 10 and 50:
R
Копировать код
runif(5, min = 10, max = 50)
3. Random Integers
Use sample() to generate random integers within a specific range:
R
Копировать код
sample(min:max, size, replace = TRUE)
Example: Generate 5 random integers between 1 and 100:
R
Копировать код
sample(1:100, 5, replace = TRUE)
4. Repeatable Random Numbers (Set a Seed)
To ensure reproducibility, set a seed before generating random numbers:
R
Копировать код
set.seed(42) # Choose any number
runif(5)
Every time you run this code with the same seed, you will get the same random numbers.
—--------------------------------------------------------------------------------------------------------
rnorm() is a function in R, commonly used to generate random numbers from a normal
(Gaussian) distribution. It is part of R's base package and does not require any additional
libraries to use.
Syntax
R
Копировать код
rnorm(n, mean = 0, sd = 1)
Arguments
● n: The number of random numbers to generate.
● mean: The mean (average) of the normal distribution (default is 0).
● sd: The standard deviation of the normal distribution (default is 1).
Return Value
A numeric vector of length n containing random numbers sampled from the specified normal
distribution.
Example Usage
Generate 10 random numbers from a standard normal distribution (mean = 0, sd = 1):
R
Копировать код
rnorm(10)
1.
Generate 5 random numbers from a normal distribution with mean = 5 and sd = 2:
R
Копировать код
rnorm(5, mean = 5, sd = 2)
2.
Store the results in a variable:
R
Копировать код
random_numbers <- rnorm(100, mean = 50, sd = 10)
summary(random_numbers)
3.
This function is commonly used in statistical simulations and probabilistic modeling.
—----------------------------------------------------------------------------------------------
Uniform Distribution
● runif(n, min = 0, max = 1): Generates n random numbers from a uniform
distribution between min and max(default: 0 and 1).
Normal Distribution
● rnorm(n, mean = 0, sd = 1): Generates n random numbers from a normal
distribution with specified mean and standard deviation.