R - 正态分布


在从独立来源随机收集数据时,通常观察到数据分布呈正态分布。这意味着,在绘制横轴为变量值、纵轴为值计数的图表时,我们得到一条钟形曲线。曲线的中心代表数据集的平均值。在图表中,百分之五十的值位于平均值的左侧,其余百分之五十位于图表的右侧。这在统计学中称为正态分布。

R 有四个内置函数来生成正态分布。它们的描述如下。

dnorm(x, mean, sd)
pnorm(x, mean, sd)
qnorm(p, mean, sd)
rnorm(n, mean, sd)

以下是上述函数中使用的参数的描述 -

  • x是数字向量。

  • p是概率向量。

  • n是观察次数(样本大小)。

  • 平均值是样本数据的平均值。它的默认值为零。

  • sd是标准差。它的默认值为 1。

dnorm()

该函数给出给定均值和标准差的每个点的概率分布高度。

# Create a sequence of numbers between -10 and 10 incrementing by 0.1.
x <- seq(-10, 10, by = .1)

# Choose the mean as 2.5 and standard deviation as 0.5.
y <- dnorm(x, mean = 2.5, sd = 0.5)

# Give the chart file a name.
png(file = "dnorm.png")

plot(x,y)

# Save the file.
dev.off()

当我们执行上面的代码时,它会产生以下结果 -

dnorm() 图

pnorm()

该函数给出正态分布的随机数小于给定数字的值的概率。它也被称为“累积分布函数”。

# Create a sequence of numbers between -10 and 10 incrementing by 0.2.
x <- seq(-10,10,by = .2)
 
# Choose the mean as 2.5 and standard deviation as 2. 
y <- pnorm(x, mean = 2.5, sd = 2)

# Give the chart file a name.
png(file = "pnorm.png")

# Plot the graph.
plot(x,y)

# Save the file.
dev.off()

当我们执行上面的代码时,它会产生以下结果 -

pnorm() 图

qnorm()

该函数获取概率值并给出一个累积值与概率值匹配的数字。

# Create a sequence of probability values incrementing by 0.02.
x <- seq(0, 1, by = 0.02)

# Choose the mean as 2 and standard deviation as 3.
y <- qnorm(x, mean = 2, sd = 1)

# Give the chart file a name.
png(file = "qnorm.png")

# Plot the graph.
plot(x,y)

# Save the file.
dev.off()

当我们执行上面的代码时,它会产生以下结果 -

qnorm() 图

rnorm()

该函数用于生成服从正态分布的随机数。它将样本大小作为输入并生成许多随机数。我们画一个直方图来显示生成数字的分布。

# Create a sample of 50 numbers which are normally distributed.
y <- rnorm(50)

# Give the chart file a name.
png(file = "rnorm.png")

# Plot the histogram for this sample.
hist(y, main = "Normal DIstribution")

# Save the file.
dev.off()

当我们执行上面的代码时,它会产生以下结果 -

rnorm() 图