# Truncated Normal Distribution

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Many distributions may be used to describe patterns that are non-negative; however, there are not as many choices when an upper bound is also needed (although the beta distribution is very flexible). For various reasons, truncated distributions are sometimes preferred, and the truncated normal is particularly popular. While R has a package that includes the standard functions for this distribution (see rtnorm, dtnorm, etc. in the msm pacakge), the true expectation and variance of the distribution may be of interest. It turns out that the first two moments of the truncated normal are not too hard to calculate (but worth writing functions for):**Quantitative Ecology**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

mean.tnorm<-function(mu,sd,lower,upper){ ##return the expectation of a truncated normal distribution lower.std=(lower-mu)/sd upper.std=(upper-mu)/sd mean=mu+sd*(dnorm(lower.std)-dnorm(upper.std))/ (pnorm(upper.std)-pnorm(lower.std)) return(mean) } var.tnorm<-function(mu,sd,lower,upper){ ##return the variance of a truncated normal distribution lower.std=(lower-mu)/sd upper.std=(upper-mu)/sd variance=sd^2*(1+(lower.std*dnorm(lower.std)-upper.std*dnorm(upper.std))/ (pnorm(upper.std)-pnorm(lower.std))-((dnorm(lower.std)-dnorm(upper.std))/ (pnorm(upper.std)-pnorm(lower.std)))^2) return(variance) } ###Testing > library(msm) > a=rtnorm(1000000,-5,2,1,3) > paste(mean(a),var(a)) [1] "1.52135857341077 0.197281057170982" > paste(mean.tnorm(-5,2,1,3),var.tnorm(-5,2,1,3)) [1] "1.52090857118 0.197111175109889"

To

**leave a comment**for the author, please follow the link and comment on their blog:**Quantitative Ecology**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.