# R code for Lecture 1 # Example 1 in chapter 0 X <- c(1.84, 1.67, 1.68, 1.42, 1.54, 1.59, 1.60, 1.74, 1.83, 1.65, 1.51, 1.80, 1.64, 1.80, 1.62, 1.67, 1.67, 1.69, 1.74, 1.73) # calculate sample mean, sample variance and standard deviation. sm <- mean(X) sv <- var(X) sd <- sd(X) sm; sv; sd # generate the histogram hist(X) # Example 2 alp <- 0.01 n <- length(X) # calculate T-statistic T <- (sm - 1.65)/(sd/sqrt(n)) # calculate (1 - alpha/2)-quantile of t-distribution with df (n-1) qt <- qt(1-alp/2, n-1) T; qt # Example 3 # calculate (1 - alpha/2)-quantile of t-distribution with df (n-1) alp <- c(0.1, 0.05, 0.01) qnorm(1-alp/2) v<- c(2, 10) qt(0.975, v) v <- c(10, 5) qchisq(0.95, v) alp <-c(0.95, 0.99); v1 <-c(4, 2); v2 <-c(10, 20) qf(alp, v1, v2) # Example 4 X <- rbind(c(1.84,91.31), c(1.67, 88.63), c(1.68, 83.94), c(1.42, 75.55), c(1.54, 79.57), c(1.59, 82.68), c(1.60, 80.41), c(1.74, 82.42), c(1.83, 92.21), c(1.65, 79.63), c(1.51, 71.15), c(1.80, 95.24), c(1.64, 77.38), c(1.80, 91.67), c(1.62, 79.57), c(1.67, 80.64), c(1.67, 87.26), c(1.69, 89.52), c(1.74, 93.50), c(1.73, 88.57)) # calcuate the sample varaicne and covariance Sh <- sd(X[,1]); Sw <- sd(X[,2]) Shw <- cov(X[,1], X[,2]) Sh; Sw; Shw # calculate the correlation coefficient rho <- Shw/(Sh*Sw); rho cor(X[,1], X[,2]) # generate scatterplot plot(X[,1], X[,2], main="Scatterplot Example") # R code for Chapter 1 (Part 1) # Example 1 X <- c(1.0, 1.5, 2.1, 2.9, 3.2, 3.9) Y <- c(0.60, 2.00, 1.06, 3.44, 1.17, 3.54) mX <- mean(X); mY <-mean(Y) sXY <- sum((X - mX)*(Y -mY)) sX <- sum((X - mX)^2) b1 <- sXY/sX; b0 <- mY - b1*mX b0; b1 Y_hat <- b0 + b1*X res <- Y - Y_hat Z <- cbind(X, Y, Y_hat, res) Z