A Guide To Dnorm, Pnorm, Qnorm, and Rnorm in R
A Guide To Dnorm, Pnorm, Qnorm, and Rnorm in R
rnorm in R
dnorm
The function dnorm returns the value of the probability density function
(pdf) of the normal distribution given a certain random variable x, a
population mean μ and population standard deviation σ. The syntax for
using dnorm is as follows:
dnorm(x, mean, sd)
#find the value of the normal distribution pdf at x=10 with mean=20 and sd=5
dnorm(x=10, mean=20, sd=5)
# [1] 0.01079819
#create a vector of values that shows the height of the probability distribution
#for each value in x
y <- dnorm(x)
#plot x and y as a scatterplot with connected lines (type = "l") and add
#an x-axis with custom labels
plot(x,y, type = "l", lwd = 2, axes = FALSE, xlab = "", ylab = "")
axis(1, at = -3:3, labels = c("-3s", "-2s", "-1s", "mean", "1s", "2s", "3s"))
pnorm(q, mean, sd)
# [1] 0.02275013
# [1] 0.05479929
# [1] 0.6246553
qnorm(p, mean, sd)
Put simply, you can use qnorm to find out what the Z-score is of the
pth quantile of the normal distribution.
#find the Z-score of the 95th quantile of the standard normal distribution
qnorm(.95)
# [1] 1.644854
#find the Z-score of the 10th quantile of the standard normal distribution
qnorm(.10)
# [1] -1.281552
rnorm
The function rnorm generates a vector of normally distributed random
variables given a vector length n, a population mean μ and population
standard deviation σ. The syntax for using rnorm is as follows:
Report this ad
rnorm(n, mean, sd)
#generate a vector of 1000 normally distributed random variables with mean=50 and sd=5
narrowDistribution <- rnorm(1000, mean = 50, sd = 15)
#generate a vector of 1000 normally distributed random variables with mean=50 and sd=25
wideDistribution <- rnorm(1000, mean = 50, sd = 25)
#generate two histograms to view these two distributions side by side, specify
#50 bars in histogram and x-axis limits of -50 to 150
par(mfrow=c(1, 2)) #one row, two columns
hist(narrowDistribution, breaks=50, xlim=c(-50, 150))
hist(wideDistribution, breaks=50, xlim=c(-50, 150))
Notice how the wide distribution is much more spread out compared to
the narrow distribution. This is because we specified the standard
deviation in the wide distribution to be 25 compared to just 15 in the
narrow distribution. Also notice that both histograms are centered around
the mean of 50.