Examples
\begin{xmpl}
Simulating and plotting a single normal distribution.
$Y \sim n(0,1)$
\begin{lstlisting}
library(MASS) # for truehist
par(mfcol=c(2,2))
y<-rnorm(1000) # generating 1000 n(0,1)
mn<-mean(y)
vr<-var(y)
truehist(y,ymax=0.5) # plot the histogram
xvec<-seq(-4,4,0.01) # generate the x-axis
yvec<-dnorm(xvec) # theoretical n(0,1) density
lines(xvec,yvec,lwd=2,col="red")
ttl<-paste("Simulation and theory n(0,1)\n",
"mean=",round(mn,2),
"and variance=",round(vr,2))
title(ttl)
\end{lstlisting}
\end{xmpl}
\begin{xmpl}
Sum of two normal distributions.
$$Y_1 \sim n(2, 2^2)$$ and $$Y_2 \sim n(3, 3^2)$$
\begin{lstlisting}
y1<-rnorm(10000,2,2) # n(2,2^2)
y2<-rnorm(10000,3,3) # n(3, 3^2)
y<-y1+y2
truehist(y)
xvec<-seq(-10,20,0.01)
# check
mn<-mean(y)
vr<-var(y)
cat("The mean is",mn,"\n")
cat("The variance is ",vr,"\n")
cat("The standard deviation is",sd(y),"\n")
yvec<-dnorm(xvec,mean=5,sd=sqrt(13)) # n() density
lines(xvec,yvec,lwd=2,col="red")
ttl<-paste("The sum of n(2,2^2) and n(3,3^2)\n",
"mean=",round(mn,2),
"and variance=",round(vr,2))
title(ttl)
\end{lstlisting}
\end{xmpl}
\begin{xmpl}
Sum of nine normal distributions, all with $\mu = 42$ and $\sigma^2=2^2$
\begin{lstlisting}
ymat<-matrix(rnorm(10000*9,42,2),ncol=9)
y<-apply(ymat,1,mean)
truehist(y)
# check
mn<-mean(y)
vr<-var(y)
cat("The mean is",mn,"\n")
cat("The variance is ",vr,"\n")
cat("The standard deviation is",sd(y),"\n")
# plot the theoretical curve
xvec<-seq(39,45,0.01)
yvec<-dnorm(xvec,mean=5,sd=sqrt(13)) # n() density
lines(xvec,yvec,lwd=2,col="red")
ttl<-paste("The sum of nine n(42^2) \n",
"mean=",round(mn,2),
"and variance=",round(vr,2))
title(ttl)
\end{lstlisting}
\end{xmpl}