#### Drawing from a standard normal distribution and checking that #### the histogram and empirical cdf resemble the density and cdf, respectively n<-1000 x<-rnorm(n,0,1) hist(x,freq=FALSE) ## empirical density t<-c(-300:300)/100 lines(t,dnorm(t,0,1)) ## true density plot(ecdf(x)) ## empirical cdf lines(t,pnorm(t,0,1),col=2) ## true cdf s<-c(1:n)/n plot(s,qnorm(s,0,1)) ## true inverse cdf x.sort<-sort(x) lines(s,x.sort[s*n],col=2,lwd=3) ## empirical inverse cdf plot(x.sort[s*n],qnorm(s,0,1),main="q-q plot") ## QQ-plot: true inverse cdf versus empirical inverse cdf abline(0,1) #### Drawing from a chi-square distribution with 1 degree of freedom n<-1000 x<-rchisq(n,1) hist(x,freq=FALSE) t<-c(0:1200)/100 lines(t,dchisq(t,1)) plot(ecdf(x)) lines(t,pchisq(t,1),col=2) #### Creating a chi-square distribution by squaring a standard normal random variable z<-rnorm(n,0,1) hist(z) y<-z^2 hist(y,freq=FALSE) lines(t,dchisq(t,1)) #### Probability-integral transformation: Drawing Z from N(0,1), computing Y=F_Z(Z), and showing that Y~UNIF(0,1) n<-10000 z<-rnorm(n,0,1) y<-pnorm(z,0,1) hist(y,freq=FALSE) lines(s,dunif(s,0,1)) #### Drawing from an exponential distribution n<-10000 x<-rexp(n,1) hist(x,freq=FALSE) t<-c(0:1200)/100 lines(t,dexp(t,1)) plot(ecdf(x)) lines(t,pexp(t,1),col=2) y<-pexp(x,1) ### probability-integral transformation hist(y,freq=FALSE) s<-c(0:100)/100 lines(s,dunif(s,0,1)) #### Now generating U~UNIF(0,1) and creating Z~EXP(1) using inverse-probability-integral transformation u<-runif(n,0,1) z<-qexp(u,1) #### Doing it using quantile function for Exponentials hist(z,freq=FALSE) t<-c(0:1200)/100 lines(t,dexp(t,1)) z1<--log(1-u) #### Doing it using direct calculations hist(z1,freq=FALSE) lines(t,dexp(t,1))