R rnorm() function - Generate normal distribution random numbers

R 语言实例R Language Examples

The R rnorm() function is used to generate random numbers that follow a normal distribution (Gaussian distribution).

The normal distribution is the most common distribution in nature and is widely used in statistical analysis and simulation experiments.

The syntax format of the rnorm() function is as follows:

rnorm(n, mean = 0, sd = 1)

Parameter description:

  • nNumber of random numbers to generate.

  • meanThe mean of the normal distribution, default is 0.

  • sdThe standard deviation of the normal distribution, default is 1.

Example

# Set a random seed to ensure reproducible results
set.seed(123)

# Generate 10 standard normal distribution random numbers
random_nums <- rnorm(10)
print("Standard normal distribution random numbers:")
print(round(random_nums, 4))

# Generate random numbers with mean 70 and standard deviation 10 (simulating exam scores)
set.seed(123)
scores <- rnorm(1000, mean = 70, sd = 10)
print(paste("Mean of 1000 generated scores:", round(mean(scores), 2)))
print(paste("Standard deviation:", round(sd(scores), 2)))

# View the distribution
print(summary(scores))

Executing the above code outputs the following result:

[1] "标准正态分布随机数:"
 [1] -0.5605 -0.2302  1.5587  0.0705  0.1293
 [6]  1.7151  0.4609 -1.2651 -0.6869 -0.4457
[1] "生成 1000 个成绩的均值: 69.97"
[1] "标准差: 10.03"
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  32.69   63.36   69.82   69.97   76.55  106.42

R 语言实例R Language Examples

Other Extensions