# central_limit_theorem.R
# Demonstration of central limit theorem in action

# Load necessary libraries
library(ggplot2)
library(psych)

# Generate 100000 random observations
n <- 100000

# A single Poisson observation with lambda = 1
y1 <- rpois(n,1)

# Mean of 5 Poisson observations
y5 <- rpois(5*n,1)
y5 <- matrix(y5,n,5)
y5 <- apply(y5,1,mean)

# Mean of 10 Poisson observations
y10 <- rpois(10*n,1)
y10 <- matrix(y10,n,10)
y10 <- apply(y10,1,mean)

# Mean of 50 Poisson observations
y50 <- rpois(50*n,1)
y50 <- matrix(y50,n,50)
y50 <- apply(y50,1,mean)             

# Make data frame for ggplot2
plotdata <- as.data.frame(cbind(y1,y5,y10,y50))

# Print first 25 observations
plotdata[1:25,]

# Graphics using ggplot2
ggplot(plotdata,aes(y1))+
geom_histogram(binwidth=0.1)
ggplot(plotdata,aes(y5))+
geom_histogram(binwidth=0.06)
ggplot(plotdata,aes(y10))+
geom_histogram(binwidth=0.04)
ggplot(plotdata,aes(y50))+
geom_histogram(binwidth=0.015)

# Normal quantile plots
qqnorm(y1,main="y1")
qqnorm(y5,main="y5")
qqnorm(y10,main="y10")
qqnorm(y50,main="y50")

# Descriptive statistics
describe(plotdata)
