# Linear.R
# Demonstration of expected value and variance rules

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

# Generate 100000 random observations
n <- 100000
a <- 2
b <- 1

# Generate y, y1, y2, y3 with N(1,2) distribution
mu <- 1
sig2 <- 1
y <- rnorm(n,mu,sqrt(sig2))
y1 <- rnorm(n,mu,sqrt(sig2))
y2 <- rnorm(n,mu,sqrt(sig2))
y3 <- rnorm(n,mu,sqrt(sig2))

# Calculate a linear function of y, then sum, mean, and s2
yprime <- a*y + b
y123 <- cbind(y1,y2,y3)
ysum <- apply(y123,1,sum)
ybar <- apply(y123,1,mean)
s2 <- apply(y123,1,var)

# Make data frame for ggplot2
plotdata <- as.data.frame(cbind(y,yprime,ysum,ybar,s2))

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

# Graphics using ggplot2
ggplot(plotdata,aes(y))+
geom_histogram()+xlim(-6,12)
ggplot(plotdata,aes(yprime))+
geom_histogram()+xlim(-6,12)
ggplot(plotdata,aes(ysum))+
geom_histogram()+xlim(-6,12)
ggplot(plotdata,aes(ybar))+
geom_histogram()+xlim(-6,12)
ggplot(plotdata,aes(s2))+
geom_histogram()+xlim(-6,12)

# Normal quantile plots
qqnorm(y,main="y")
qqnorm(yprime,main="yprime")
qqnorm(ysum,main="ysum")
qqnorm(ybar,main="ybar")
qqnorm(s2,main="s2")

# Descriptive statistics
describe(plotdata)
