The dnorm() in R

dnorm in r

The dnorm() function in R is a function in the norm family function (dnorm(), pnorm(), qnorm(), rnorm()). The function() calculates the normal distribution’s probability density function (PDF). Keep reading the article, and we will show you how to use the function. 

Normal distribution and probability density function (PDF)

Before learning about the dnorm() function, we will remind you of the normal distribution and its probability density function (PDF).

A continuous random variable x is said to have the normal distribution with the mean \mu and the standard deviation \sigma > 0 , if the probability density function (PDF) is:

\frac { 1 } { \sqrt { 2 \pi } \sigma } e^{ -(x - \mu)^2/2 \sigma^2}

The dnorm() function 

Make sure that you remember the normal distribution and the probability density function. Next, we will discover the dnorm() function.

Syntax:

dnorm(x, mean, sd)

Parameters:

  • x: A random variable vector
  • mean: The mean of the vector’s elements
  • sd: The standard deviation of the vector’s elements

Some examples of the dnorm() function

Below are a few examples of using the dnorm() function to calculate and represent the normal distribution and its probability density values.

Calculate the probability density function of the normal distribution

Because the normal distribution distributes balance around zero, we will create a vector having elements from -5 to 5. Then, use the dnorm() function to calculate the probability density values of the vector with a mean equal to 0 and a standard deviation equal to 1. Finally, we get the results symmetrical by the middle value.

Code:

# Create a vector x having balance values around 0
x <- seq(-5, 5, by = 1)

# Calculate the probability density of the vector x
y <- dnorm(x, mean = 0, sd = 1)

cat("The probability density values of x are:\n")
cat(y)

Result:

The probability density values of x are:
1.48672e-06 0.0001338302 0.004431848 0.05399097 0.2419707 0.3989423 0.2419707 0.05399097 0.004431848 0.0001338302 1.48672e-06

Visualize the probability density function of the normal distribution

To be more intuitive, we will visualize the results by using the plot() function.

Code:

# Create a vector x having balance values around 0
x <- seq(-5, 5, by = 0.0001)

# Calculate the probability density of the vector x
y <- dnorm(x)

plot(y, col = "red", main = "The probability density values of the vector x", col.main = "blue")

Result:

Summary

In summary, the dnorm() function calculates the value of the probability density function of the normal distribution. Although the function is simple, it has many applications in practice. We hope you understand both knowledge in math and programming.

Maybe you are interested:

Posted in R

Leave a Reply

Your email address will not be published. Required fields are marked *