################################################################################ #### Special Continous Distributions #### ################################################################################ #### By Jimin Ding, 02/05/2017 ## set seed to make random simulation fixed set.seed(900) ########### 1. Normal Distribution ?rnorm ## cdf: given x, find the probabilities of X < x ## Same as table A.3 on page 673-674 of the textbook pnorm(-0.2,mean=0,sd=1) pnorm(16,mean=16.1,sd=0.5) ## quantile function qnorm(0.5,mean=16.1,sd=0.5) qnorm(0.4207,mean=16.1,sd=0.5) ## plot PDF and CDF x=seq(from=-2,to=4,by=0.01) Fx=pnorm(x) fx=dnorm(x) par(mfrow=c(1,2)) plot(x,Fx,main="CDF of N(0,1)",pch='.') plot(x,fx,main="PDF of N(0,1)",pch='.') abline(v=0,lty=3,col='red') ########### 2. LogNormal Distribution ?rlnorm y=rlnorm(10000) par(mfrow=c(1,2)) hist(y) hist(log(y)) ## Note the parameters, meanlog and sdlog, are not the mean and standard deviation of the random variable, ## but the mean and standard deviation of the log(y)! mean(y) sd(y) mean(log(y)) sd(log(y)) pdf("logNorm.pdf",height=5) par(mfrow=c(1,2)) x=(0:2000)/100 plot(x,dlnorm(x,meanlog=0,sdlog=1),type='l',col='red',lwd=2, xlim=c(-1,15),ylim=c(0,1),ylab='f(x)',main='PDF of LogNormal') lines(x,dlnorm(x,meanlog=1,sdlog=1),col='blue',lwd=2) lines(x,dlnorm(x,meanlog=0,sdlog=2),col='black',lwd=2) legend('topright',c('mu=0,sigma=1','mu=1,sigma=1','mu=0,sigma=2'), lty=1,lwd=2,col=c('red','blue','black')) plot(x,plnorm(x,meanlog=0,sdlog=1),type='l',col='red',lwd=2, xlim=c(-1,15),ylim=c(0,1),ylab='f(x)',main='CDF of LogNormal') lines(x,plnorm(x,meanlog=1,sdlog=1),col='blue',lwd=2) lines(x,plnorm(x,meanlog=0,sdlog=2),col='black',lwd=2) dev.off() ########### 3. Uniform Distribution ?runif x=runif(1000) hist(x) ## cdf: given x, find the probabilities of X < x punif(0.5,min=0,max=2) ## given probability, find the x (quantile function) ## For example, find median of U(0,2) qunif(0.5,min=0,max=2) ## plot PDF and CDF x=seq(from=-2,to=4,by=0.01) Fx=punif(x,min=0,max=2) fx=dunif(x,min=0,max=2) par(mfrow=c(1,2)) plot(x,Fx,main="CDF of U(0,2)",pch='.') plot(x,fx,main="PDF of U(0,2)",pch='.') ########### 4. Exponential Distribution ?rexp ## plot PDF and CDF x=seq(from=-2,to=4,by=0.01) Fx=pexp(x) fx=dexp(x) par(mfrow=c(1,2)) plot(x,Fx,main="CDF of EXP(1)",pch='.') plot(x,fx,main="PDF of EXP(1)",pch='.')